Sending email in python (MIMEmultipart)2019 Community Moderator ElectionHow to validate an email address in JavaScript?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonHow to validate an email address using a regular expression?Difference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonDoes Python have a string 'contains' substring method?
Why is a very small peak with larger m/z not considered to be the molecular ion?
Confusion about Complex Continued Fraction
How many characters using PHB rules does it take to be able to have access to any PHB spell at the start of an adventuring day?
Possible to detect presence of nuclear bomb?
Are all players supposed to be able to see each others' character sheets?
Is it possible that a question has only two answers?
Do cubics always have one real root?
Can the alpha, lambda values of a glmnet object output determine whether ridge or Lasso?
What is Tony Stark injecting into himself in Iron Man 3?
In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?
Why do we say ‘pairwise disjoint’, rather than ‘disjoint’?
Was it really inappropriate to write a pull request for the company I interviewed with?
School performs periodic password audits. Is my password compromised?
How to resolve: Reviewer #1 says remove section X vs. Reviewer #2 says expand section X
Are there historical instances of the capital of a colonising country being temporarily or permanently shifted to one of its colonies?
Can I negotiate a patent idea for a raise, under French law?
What is the generally accepted pronunciation of “topoi”?
Rationale to prefer local variables over instance variables?
How do electrons receive energy when a body is heated?
Is it possible to find 2014 distinct positive integers whose sum is divisible by each of them?
Source permutation
What will happen if my luggage gets delayed?
Is it safe to abruptly remove Arduino power?
Doesn't allowing a user mode program to access kernel space memory and execute the IN and OUT instructions defeat the purpose of having CPU modes?
Sending email in python (MIMEmultipart)
2019 Community Moderator ElectionHow to validate an email address in JavaScript?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonHow to validate an email address using a regular expression?Difference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonDoes Python have a string 'contains' substring method?
How should I send an email with text format and html format in the same body? What is the use of MIMEmultipart
?
MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
I was able to receive an email using this but with a blank body
PS: I am trying to send a text and attach a table in the same body. I don't want to send a table as an attachment.
html = """
<html>
<head>
<style>
table, th, td border: 1px solid black; border-collapse: collapse; th, td padding: 5px;
</style>
</head>
<body><p>Hello, Friend This data is from a data frame.</p>
<p>Here is your data:</p>
table
<p>Regards,</p>
<p>Me</p>
</body>
</html> """
text = """
Hello, Friend.
Here is your data:
table
Regards,
Me"""
text = text.format(table=tabulate(df, headers=list(df.columns), tablefmt="grid"))
html = html.format(table=tabulate(df, headers=list(df.columns), tablefmt="html"))
if(df['date'][0].year==1900 and df['date'][0].month==datetime.date.today().month and df['date'][0].day==datetime.date.today().day):
a2=smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
a2.starttls()
myadd='abc@gmail.com'
passwd=getpass.getpass(prompt='Password: ')
try :
a2.login(myadd,passwd)
except Exception :
print("login unsuccessful")
def get_contacts(filename):
name=[]
email=[]
with open('email.txt','r') as fl:
l=fl.readlines()
print(l)
print(type(l))
for i in l:
try:
name.append(i.split('n')[0].split()[0])
email.append(i.split('n')[0].split()[1])
except Exception:
break
fl.close()
return (name,email)
def temp_message(filename):
with open(filename,'r') as fl1:
l2=fl1.read()
return(Template(l2))
name,email=get_contacts('email.txt')
tmp1=temp_message('temp1.txt')
for name,eml in zip(name,email):
msg=MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
message=tmp1.substitute(USER_NAME=name.title())
print(message)
msg['FROM']=myadd
msg['TO']=eml
msg['Subject']="This is TEST"
msg.attach(MIMEText(message, 'plain'))
# msg.set_payload([MIMEText(message, 'plain'),MIMEText(html, 'html')])
# send the message via the server set up earlier.
a2.send_message(msg)
del msg
a2.quit()
python python-3.x email mime smtplib
add a comment |
How should I send an email with text format and html format in the same body? What is the use of MIMEmultipart
?
MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
I was able to receive an email using this but with a blank body
PS: I am trying to send a text and attach a table in the same body. I don't want to send a table as an attachment.
html = """
<html>
<head>
<style>
table, th, td border: 1px solid black; border-collapse: collapse; th, td padding: 5px;
</style>
</head>
<body><p>Hello, Friend This data is from a data frame.</p>
<p>Here is your data:</p>
table
<p>Regards,</p>
<p>Me</p>
</body>
</html> """
text = """
Hello, Friend.
Here is your data:
table
Regards,
Me"""
text = text.format(table=tabulate(df, headers=list(df.columns), tablefmt="grid"))
html = html.format(table=tabulate(df, headers=list(df.columns), tablefmt="html"))
if(df['date'][0].year==1900 and df['date'][0].month==datetime.date.today().month and df['date'][0].day==datetime.date.today().day):
a2=smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
a2.starttls()
myadd='abc@gmail.com'
passwd=getpass.getpass(prompt='Password: ')
try :
a2.login(myadd,passwd)
except Exception :
print("login unsuccessful")
def get_contacts(filename):
name=[]
email=[]
with open('email.txt','r') as fl:
l=fl.readlines()
print(l)
print(type(l))
for i in l:
try:
name.append(i.split('n')[0].split()[0])
email.append(i.split('n')[0].split()[1])
except Exception:
break
fl.close()
return (name,email)
def temp_message(filename):
with open(filename,'r') as fl1:
l2=fl1.read()
return(Template(l2))
name,email=get_contacts('email.txt')
tmp1=temp_message('temp1.txt')
for name,eml in zip(name,email):
msg=MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
message=tmp1.substitute(USER_NAME=name.title())
print(message)
msg['FROM']=myadd
msg['TO']=eml
msg['Subject']="This is TEST"
msg.attach(MIMEText(message, 'plain'))
# msg.set_payload([MIMEText(message, 'plain'),MIMEText(html, 'html')])
# send the message via the server set up earlier.
a2.send_message(msg)
del msg
a2.quit()
python python-3.x email mime smtplib
Show us your code! What have you tried, what do you expect, and where are you having trouble?
– David Cain
Mar 7 at 4:47
@DavidCain I have updated the body. My problem is in MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
– Vineeth Ananthula
Mar 7 at 5:17
add a comment |
How should I send an email with text format and html format in the same body? What is the use of MIMEmultipart
?
MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
I was able to receive an email using this but with a blank body
PS: I am trying to send a text and attach a table in the same body. I don't want to send a table as an attachment.
html = """
<html>
<head>
<style>
table, th, td border: 1px solid black; border-collapse: collapse; th, td padding: 5px;
</style>
</head>
<body><p>Hello, Friend This data is from a data frame.</p>
<p>Here is your data:</p>
table
<p>Regards,</p>
<p>Me</p>
</body>
</html> """
text = """
Hello, Friend.
Here is your data:
table
Regards,
Me"""
text = text.format(table=tabulate(df, headers=list(df.columns), tablefmt="grid"))
html = html.format(table=tabulate(df, headers=list(df.columns), tablefmt="html"))
if(df['date'][0].year==1900 and df['date'][0].month==datetime.date.today().month and df['date'][0].day==datetime.date.today().day):
a2=smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
a2.starttls()
myadd='abc@gmail.com'
passwd=getpass.getpass(prompt='Password: ')
try :
a2.login(myadd,passwd)
except Exception :
print("login unsuccessful")
def get_contacts(filename):
name=[]
email=[]
with open('email.txt','r') as fl:
l=fl.readlines()
print(l)
print(type(l))
for i in l:
try:
name.append(i.split('n')[0].split()[0])
email.append(i.split('n')[0].split()[1])
except Exception:
break
fl.close()
return (name,email)
def temp_message(filename):
with open(filename,'r') as fl1:
l2=fl1.read()
return(Template(l2))
name,email=get_contacts('email.txt')
tmp1=temp_message('temp1.txt')
for name,eml in zip(name,email):
msg=MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
message=tmp1.substitute(USER_NAME=name.title())
print(message)
msg['FROM']=myadd
msg['TO']=eml
msg['Subject']="This is TEST"
msg.attach(MIMEText(message, 'plain'))
# msg.set_payload([MIMEText(message, 'plain'),MIMEText(html, 'html')])
# send the message via the server set up earlier.
a2.send_message(msg)
del msg
a2.quit()
python python-3.x email mime smtplib
How should I send an email with text format and html format in the same body? What is the use of MIMEmultipart
?
MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
I was able to receive an email using this but with a blank body
PS: I am trying to send a text and attach a table in the same body. I don't want to send a table as an attachment.
html = """
<html>
<head>
<style>
table, th, td border: 1px solid black; border-collapse: collapse; th, td padding: 5px;
</style>
</head>
<body><p>Hello, Friend This data is from a data frame.</p>
<p>Here is your data:</p>
table
<p>Regards,</p>
<p>Me</p>
</body>
</html> """
text = """
Hello, Friend.
Here is your data:
table
Regards,
Me"""
text = text.format(table=tabulate(df, headers=list(df.columns), tablefmt="grid"))
html = html.format(table=tabulate(df, headers=list(df.columns), tablefmt="html"))
if(df['date'][0].year==1900 and df['date'][0].month==datetime.date.today().month and df['date'][0].day==datetime.date.today().day):
a2=smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
a2.starttls()
myadd='abc@gmail.com'
passwd=getpass.getpass(prompt='Password: ')
try :
a2.login(myadd,passwd)
except Exception :
print("login unsuccessful")
def get_contacts(filename):
name=[]
email=[]
with open('email.txt','r') as fl:
l=fl.readlines()
print(l)
print(type(l))
for i in l:
try:
name.append(i.split('n')[0].split()[0])
email.append(i.split('n')[0].split()[1])
except Exception:
break
fl.close()
return (name,email)
def temp_message(filename):
with open(filename,'r') as fl1:
l2=fl1.read()
return(Template(l2))
name,email=get_contacts('email.txt')
tmp1=temp_message('temp1.txt')
for name,eml in zip(name,email):
msg=MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
message=tmp1.substitute(USER_NAME=name.title())
print(message)
msg['FROM']=myadd
msg['TO']=eml
msg['Subject']="This is TEST"
msg.attach(MIMEText(message, 'plain'))
# msg.set_payload([MIMEText(message, 'plain'),MIMEText(html, 'html')])
# send the message via the server set up earlier.
a2.send_message(msg)
del msg
a2.quit()
python python-3.x email mime smtplib
python python-3.x email mime smtplib
edited Mar 7 at 7:16
vahdet
2,06431435
2,06431435
asked Mar 7 at 4:46
Vineeth AnanthulaVineeth Ananthula
156
156
Show us your code! What have you tried, what do you expect, and where are you having trouble?
– David Cain
Mar 7 at 4:47
@DavidCain I have updated the body. My problem is in MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
– Vineeth Ananthula
Mar 7 at 5:17
add a comment |
Show us your code! What have you tried, what do you expect, and where are you having trouble?
– David Cain
Mar 7 at 4:47
@DavidCain I have updated the body. My problem is in MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
– Vineeth Ananthula
Mar 7 at 5:17
Show us your code! What have you tried, what do you expect, and where are you having trouble?
– David Cain
Mar 7 at 4:47
Show us your code! What have you tried, what do you expect, and where are you having trouble?
– David Cain
Mar 7 at 4:47
@DavidCain I have updated the body. My problem is in MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
– Vineeth Ananthula
Mar 7 at 5:17
@DavidCain I have updated the body. My problem is in MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
– Vineeth Ananthula
Mar 7 at 5:17
add a comment |
2 Answers
2
active
oldest
votes
You need to create the message as
MIMEMultiPart('alternative')
and then attach the two MIMEText parts.
>>> text = 'Hello World'
>>> html = '<p>Hello World</p>'
>>> msg = MIMEMultipart('alternative')
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.attach(MIMEText(text, 'plain'))
>>> msg.attach(MIMEText(html, 'html'))
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
>>> s = smtplib.SMTP('localhost:1025')
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Received:
$ python -m smtpd -n -c DebuggingServer localhost:1025
---------- MESSAGE FOLLOWS ----------
Content-Type: multipart/alternative; boundary="===============2742770895617986609=="
MIME-Version: 1.0
Subject: Hello
To: a@example.com
From: b@example.com
X-Peer: 127.0.0.1
--===============2742770895617986609==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Hello World
--===============2742770895617986609==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
<p>Hello World</p>
--===============2742770895617986609==--
------------ END MESSAGE ------------
The reworked email package (Python 3.6+) can be used to send the same message like this:
>>> from email.message import EmailMessage
>>> msg = EmailMessage()
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.set_content(text)
>>> msg.add_alternative(html, subtype='html')
>>> s.send_message(msg)
Output:
---------- MESSAGE FOLLOWS ----------
Subject: Hello
To: a@example.com
From: b@example.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="===============1374158239299927384=="
X-Peer: 127.0.0.1
--===============1374158239299927384==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Hello World
--===============1374158239299927384==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
<p>Hello World</p>
--===============1374158239299927384==--
------------ END MESSAGE ------------
add a comment |
At your 'with':
def temp_message(filename):
with open(filename,'r') as fl1:
l2=fl1.read()
Change it to:
def temp_message(filename):
filename = temp_message('temp1.txt') #changed tmp1 to filename
with open(filename, 'w+', encoding='utf-8') as fl1:
fl1.write(text)
fl1.write(html)
fl1.write(regards)
You can just split the 'regards' part of your text variable so your html(table) can be between the two. I was confused as to what your problem is (A lot of edits) but if I'm not mistaken your fl1(tempt1.txt) doesn't have any data you've only 'read'(r) the text file but didn't write anything. I would also recommend that you put your 'tmp1=temp_message('temp1.txt')' inside your
'def temp_message(filename)' to avoid confusion.
1
This is not my problem. My question is How should i send text object and html object using MIMEmultipart. I have clearly mentioned it in the question. I have pasted the code for @DavidCain requirement
– Vineeth Ananthula
Mar 7 at 6:16
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55036268%2fsending-email-in-python-mimemultipart%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You need to create the message as
MIMEMultiPart('alternative')
and then attach the two MIMEText parts.
>>> text = 'Hello World'
>>> html = '<p>Hello World</p>'
>>> msg = MIMEMultipart('alternative')
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.attach(MIMEText(text, 'plain'))
>>> msg.attach(MIMEText(html, 'html'))
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
>>> s = smtplib.SMTP('localhost:1025')
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Received:
$ python -m smtpd -n -c DebuggingServer localhost:1025
---------- MESSAGE FOLLOWS ----------
Content-Type: multipart/alternative; boundary="===============2742770895617986609=="
MIME-Version: 1.0
Subject: Hello
To: a@example.com
From: b@example.com
X-Peer: 127.0.0.1
--===============2742770895617986609==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Hello World
--===============2742770895617986609==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
<p>Hello World</p>
--===============2742770895617986609==--
------------ END MESSAGE ------------
The reworked email package (Python 3.6+) can be used to send the same message like this:
>>> from email.message import EmailMessage
>>> msg = EmailMessage()
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.set_content(text)
>>> msg.add_alternative(html, subtype='html')
>>> s.send_message(msg)
Output:
---------- MESSAGE FOLLOWS ----------
Subject: Hello
To: a@example.com
From: b@example.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="===============1374158239299927384=="
X-Peer: 127.0.0.1
--===============1374158239299927384==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Hello World
--===============1374158239299927384==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
<p>Hello World</p>
--===============1374158239299927384==--
------------ END MESSAGE ------------
add a comment |
You need to create the message as
MIMEMultiPart('alternative')
and then attach the two MIMEText parts.
>>> text = 'Hello World'
>>> html = '<p>Hello World</p>'
>>> msg = MIMEMultipart('alternative')
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.attach(MIMEText(text, 'plain'))
>>> msg.attach(MIMEText(html, 'html'))
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
>>> s = smtplib.SMTP('localhost:1025')
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Received:
$ python -m smtpd -n -c DebuggingServer localhost:1025
---------- MESSAGE FOLLOWS ----------
Content-Type: multipart/alternative; boundary="===============2742770895617986609=="
MIME-Version: 1.0
Subject: Hello
To: a@example.com
From: b@example.com
X-Peer: 127.0.0.1
--===============2742770895617986609==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Hello World
--===============2742770895617986609==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
<p>Hello World</p>
--===============2742770895617986609==--
------------ END MESSAGE ------------
The reworked email package (Python 3.6+) can be used to send the same message like this:
>>> from email.message import EmailMessage
>>> msg = EmailMessage()
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.set_content(text)
>>> msg.add_alternative(html, subtype='html')
>>> s.send_message(msg)
Output:
---------- MESSAGE FOLLOWS ----------
Subject: Hello
To: a@example.com
From: b@example.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="===============1374158239299927384=="
X-Peer: 127.0.0.1
--===============1374158239299927384==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Hello World
--===============1374158239299927384==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
<p>Hello World</p>
--===============1374158239299927384==--
------------ END MESSAGE ------------
add a comment |
You need to create the message as
MIMEMultiPart('alternative')
and then attach the two MIMEText parts.
>>> text = 'Hello World'
>>> html = '<p>Hello World</p>'
>>> msg = MIMEMultipart('alternative')
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.attach(MIMEText(text, 'plain'))
>>> msg.attach(MIMEText(html, 'html'))
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
>>> s = smtplib.SMTP('localhost:1025')
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Received:
$ python -m smtpd -n -c DebuggingServer localhost:1025
---------- MESSAGE FOLLOWS ----------
Content-Type: multipart/alternative; boundary="===============2742770895617986609=="
MIME-Version: 1.0
Subject: Hello
To: a@example.com
From: b@example.com
X-Peer: 127.0.0.1
--===============2742770895617986609==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Hello World
--===============2742770895617986609==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
<p>Hello World</p>
--===============2742770895617986609==--
------------ END MESSAGE ------------
The reworked email package (Python 3.6+) can be used to send the same message like this:
>>> from email.message import EmailMessage
>>> msg = EmailMessage()
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.set_content(text)
>>> msg.add_alternative(html, subtype='html')
>>> s.send_message(msg)
Output:
---------- MESSAGE FOLLOWS ----------
Subject: Hello
To: a@example.com
From: b@example.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="===============1374158239299927384=="
X-Peer: 127.0.0.1
--===============1374158239299927384==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Hello World
--===============1374158239299927384==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
<p>Hello World</p>
--===============1374158239299927384==--
------------ END MESSAGE ------------
You need to create the message as
MIMEMultiPart('alternative')
and then attach the two MIMEText parts.
>>> text = 'Hello World'
>>> html = '<p>Hello World</p>'
>>> msg = MIMEMultipart('alternative')
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.attach(MIMEText(text, 'plain'))
>>> msg.attach(MIMEText(html, 'html'))
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
>>> s = smtplib.SMTP('localhost:1025')
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())
Received:
$ python -m smtpd -n -c DebuggingServer localhost:1025
---------- MESSAGE FOLLOWS ----------
Content-Type: multipart/alternative; boundary="===============2742770895617986609=="
MIME-Version: 1.0
Subject: Hello
To: a@example.com
From: b@example.com
X-Peer: 127.0.0.1
--===============2742770895617986609==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Hello World
--===============2742770895617986609==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
<p>Hello World</p>
--===============2742770895617986609==--
------------ END MESSAGE ------------
The reworked email package (Python 3.6+) can be used to send the same message like this:
>>> from email.message import EmailMessage
>>> msg = EmailMessage()
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.set_content(text)
>>> msg.add_alternative(html, subtype='html')
>>> s.send_message(msg)
Output:
---------- MESSAGE FOLLOWS ----------
Subject: Hello
To: a@example.com
From: b@example.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="===============1374158239299927384=="
X-Peer: 127.0.0.1
--===============1374158239299927384==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Hello World
--===============1374158239299927384==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
<p>Hello World</p>
--===============1374158239299927384==--
------------ END MESSAGE ------------
edited yesterday
answered yesterday
snakecharmerbsnakecharmerb
11.3k42251
11.3k42251
add a comment |
add a comment |
At your 'with':
def temp_message(filename):
with open(filename,'r') as fl1:
l2=fl1.read()
Change it to:
def temp_message(filename):
filename = temp_message('temp1.txt') #changed tmp1 to filename
with open(filename, 'w+', encoding='utf-8') as fl1:
fl1.write(text)
fl1.write(html)
fl1.write(regards)
You can just split the 'regards' part of your text variable so your html(table) can be between the two. I was confused as to what your problem is (A lot of edits) but if I'm not mistaken your fl1(tempt1.txt) doesn't have any data you've only 'read'(r) the text file but didn't write anything. I would also recommend that you put your 'tmp1=temp_message('temp1.txt')' inside your
'def temp_message(filename)' to avoid confusion.
1
This is not my problem. My question is How should i send text object and html object using MIMEmultipart. I have clearly mentioned it in the question. I have pasted the code for @DavidCain requirement
– Vineeth Ananthula
Mar 7 at 6:16
add a comment |
At your 'with':
def temp_message(filename):
with open(filename,'r') as fl1:
l2=fl1.read()
Change it to:
def temp_message(filename):
filename = temp_message('temp1.txt') #changed tmp1 to filename
with open(filename, 'w+', encoding='utf-8') as fl1:
fl1.write(text)
fl1.write(html)
fl1.write(regards)
You can just split the 'regards' part of your text variable so your html(table) can be between the two. I was confused as to what your problem is (A lot of edits) but if I'm not mistaken your fl1(tempt1.txt) doesn't have any data you've only 'read'(r) the text file but didn't write anything. I would also recommend that you put your 'tmp1=temp_message('temp1.txt')' inside your
'def temp_message(filename)' to avoid confusion.
1
This is not my problem. My question is How should i send text object and html object using MIMEmultipart. I have clearly mentioned it in the question. I have pasted the code for @DavidCain requirement
– Vineeth Ananthula
Mar 7 at 6:16
add a comment |
At your 'with':
def temp_message(filename):
with open(filename,'r') as fl1:
l2=fl1.read()
Change it to:
def temp_message(filename):
filename = temp_message('temp1.txt') #changed tmp1 to filename
with open(filename, 'w+', encoding='utf-8') as fl1:
fl1.write(text)
fl1.write(html)
fl1.write(regards)
You can just split the 'regards' part of your text variable so your html(table) can be between the two. I was confused as to what your problem is (A lot of edits) but if I'm not mistaken your fl1(tempt1.txt) doesn't have any data you've only 'read'(r) the text file but didn't write anything. I would also recommend that you put your 'tmp1=temp_message('temp1.txt')' inside your
'def temp_message(filename)' to avoid confusion.
At your 'with':
def temp_message(filename):
with open(filename,'r') as fl1:
l2=fl1.read()
Change it to:
def temp_message(filename):
filename = temp_message('temp1.txt') #changed tmp1 to filename
with open(filename, 'w+', encoding='utf-8') as fl1:
fl1.write(text)
fl1.write(html)
fl1.write(regards)
You can just split the 'regards' part of your text variable so your html(table) can be between the two. I was confused as to what your problem is (A lot of edits) but if I'm not mistaken your fl1(tempt1.txt) doesn't have any data you've only 'read'(r) the text file but didn't write anything. I would also recommend that you put your 'tmp1=temp_message('temp1.txt')' inside your
'def temp_message(filename)' to avoid confusion.
edited Mar 7 at 6:01
answered Mar 7 at 5:32
IbaboiiiIbaboiii
288
288
1
This is not my problem. My question is How should i send text object and html object using MIMEmultipart. I have clearly mentioned it in the question. I have pasted the code for @DavidCain requirement
– Vineeth Ananthula
Mar 7 at 6:16
add a comment |
1
This is not my problem. My question is How should i send text object and html object using MIMEmultipart. I have clearly mentioned it in the question. I have pasted the code for @DavidCain requirement
– Vineeth Ananthula
Mar 7 at 6:16
1
1
This is not my problem. My question is How should i send text object and html object using MIMEmultipart. I have clearly mentioned it in the question. I have pasted the code for @DavidCain requirement
– Vineeth Ananthula
Mar 7 at 6:16
This is not my problem. My question is How should i send text object and html object using MIMEmultipart. I have clearly mentioned it in the question. I have pasted the code for @DavidCain requirement
– Vineeth Ananthula
Mar 7 at 6:16
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55036268%2fsending-email-in-python-mimemultipart%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Show us your code! What have you tried, what do you expect, and where are you having trouble?
– David Cain
Mar 7 at 4:47
@DavidCain I have updated the body. My problem is in MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
– Vineeth Ananthula
Mar 7 at 5:17