how to send html and text mail with python - python

I want the mail body containing html and text ,but either of them only shows up on mail body if i set the MIMEMultipart('') to MIMEMultipart('alternative') or MIMEMultipart('mixed') ,how to make them both on the mail body instead of html as attachment ?
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "my#email.com"
you = "your#email.com"
msg = MIMEMultipart('')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = 'This is text'
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.live.com', 587)
mail.ehlo()
mail.starttls()
mail.login('userName', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()

Related

I can't seem to set_content and add_alternative in the same email using python

I'm trying to create a simple email message, that has some text like "Hi John, It was great seeing you." and then at the bottom I have some html signature I want to add but I keep getting this error message:
TypeError: set_content not valid on multipart
I'm not sure what else to do, I've tried setting msg.make_alternative() and msg.make_mixed()
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = 'Reaching Out'
msg['From'] = MY_EMAIL
msg['To'] = recipient
msg.set_content(contents) # Text part of email
msg.add_alternative("""\
<!DOCTYPE html> Some HTML goes here
""", subtype='html')
# Sending Message
server = smtplib.SMTP('smtp.gmail.com', port=587)
server.starttls()
server.login(MY_EMAIL, MY_PASSWORD)
server.send_message(msg)

Want to send mail in Python with content of file as it is just like same in text file and file content into a variable

I want to send a mail with file (baba.txt) content as it is which present in file format using Python script.
For example:
this is python course.
line of code.
Thank...you....
Want same above format in mail as well. When I am trying to execute my script, it put in a single line in my mail like below
this is python course.line of code.Thank you
Here is my code:
#!/usr/bin/env python
import os
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
a=str(os.popen('cat baba.txt').read())
print("""a""")
sender_email = "asdf#gmail.com"
receiver_email = "myeamil#gmail.com"
password = ""
receiver_email_bcc = "sdfg#gmail.com"
receiver_email_bcc1 = "sdfg#gmail.com"
message = MIMEMultipart("alternative")
message["Subject"] = "Output of linux command"
message["From"] = sender_email
message["To"] = receiver_email
message["Bcc"] = receiver_email_bcc
message["Bcc"] = receiver_email_bcc1
html = """
<html>
<body>
<p>Hi Team,<br>
server output command <br>
Below are the out put of below commands: %s <br>
<br>
</p>
</body>
</html>
"""%(a,)
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(sender_email,password)
server.sendmail(sender_email, receiver_email, message.as_string())
server.close()
print ('Email sent!')
except:
print ('Email not sent!')
I want to send a mail with (baba.txt) file content as it is which present in file format using Python script including multiple line space, tab and white space.

Email using SMTP python from gmail account with html body

I am trying to send email using gmail account from python script using SMTP library. It is working fine with normal message body. But when i try to send it using HTML body. It does not allow me to send.
# Import smtplib to provide email functions
import smtplib
# Import the email modules
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Define email addresses to use
addr_to = 'xxxx#localdomain.com'
addr_from = "xxxxx#gmail.com"
# Define SMTP email server details
smtp_server = 'smtp.gmail.com'
smtp_user = 'xxxxxx#gmail.com'
smtp_pass = 'xxxxxxx'
# Construct email
msg = MIMEMultipart('alternative')
msg['To'] = *emphasized text*addr_to
msg['From'] = addr_from
msg['Subject'] = 'Test Email From RPi'
# Create the body of the message (a plain-text and an HTML version).
text = "This is a test message.\nText and html."
html = """\
<html>
<head></head>
<body>
<p>This is a test message.</p>
<p>Text and HTML</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via an SMTP server
s = smtplib.SMTP(smtp_server,587)
s.login(smtp_user,smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
Add these two lines before attempting to login, it won't gave you the authentication error.
server.ehlo()
server.starttls()
So your code should look like this:
# Import smtplib to provide email functions
import smtplib
# Import the email modules
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Define email addresses to use
addr_to = 'xxxx#localdomain.com'
addr_from = "xxxxx#gmail.com"
# Define SMTP email server details
smtp_server = 'smtp.gmail.com'
smtp_user = 'xxxxxx#gmail.com'
smtp_pass = 'xxxxxxx'
# Construct email
msg = MIMEMultipart('alternative')
msg['To'] = *emphasized text*addr_to
msg['From'] = addr_from
msg['Subject'] = 'Test Email From RPi'
# Create the body of the message (a plain-text and an HTML version).
text = "This is a test message.\nText and html."
(your html code)
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via an SMTP server
s = smtplib.SMTP(smtp_server,587)
s.ehlo()
s.starttls()
s.login(smtp_user,smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
The issue could be that google isn't letting using that service anymore as far as i know

add sender's name in the from field of the email in python

I am trying to send email with below code.
import smtplib
from email.mime.text import MIMEText
sender = 'sender#sender.com'
def mail_me(cont, receiver):
msg = MIMEText(cont, 'html')
recipients = ",".join(receiver)
msg['Subject'] = 'Test-email'
msg['From'] = "XYZ ABC"
msg['To'] = recipients
# Send the message via our own SMTP server.
try:
s = smtplib.SMTP('localhost')
s.sendmail(sender, receiver, msg.as_string())
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
finally:
s.quit()
cont = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
mail_me(cont,['xyz#xyzcom'])
I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender#sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.
[![from: XYZ#<machine-hostname-appearing-here>
reply-to: XYZ#<machine-hostname-appearing-here>,
ABC#<machine-hostname-appearing-here>][1]][1]
I have attached a screenshot of the email that i receive.
how can i fix this according to my need.
This should work:
msg['From'] = "Your name <Your email>"
Example below:
import smtplib
from email.mime.text import MIMEText
def send_email(to=['example#example.com'],
f_host='example.example.com',
f_port=587,
f_user='example#example.com',
f_passwd='example-pass',
subject='default subject',
message='content message'):
smtpserver = smtplib.SMTP(f_host, f_port)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(f_user, f_passwd) # from email credential
msg = MIMEText(message, 'html')
msg['Subject'] = 'My custom Subject'
msg['From'] = "Your name <Your email>"
msg['To'] = ','.join(to)
for t in to:
smtpserver.sendmail(f_user, t, msg.as_string()) # you just need to add
# this in for loop in
# your code.
smtpserver.close()
print('Mail is sent successfully!!')
cont = """
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
try:
send_email(message=cont)
except:
print('Mail could not be sent')
Just tested the following code with gmx.com and it works fine. Although, whether you get the same mileage is a moot point.
I have replaced all references to my email service with gmail
#!/usr/bin/python
#from smtplib import SMTP # Standard connection
from smtplib import SMTP_SSL as SMTP #SSL connection
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
sender = 'example#gmail.com'
receivers = ['example#gmail.com']
msg = MIMEMultipart()
msg['From'] = 'example#gmail.com'
msg['To'] = 'example#gmail.com'
msg['Subject'] = 'simple email via python test 1'
message = 'This is the body of the email line 1\nLine 2\nEnd'
msg.attach(MIMEText(message))
ServerConnect = False
try:
smtp_server = SMTP('smtp.gmail.com','465')
smtp_server.login('#name##gmail.com', '#password#')
ServerConnect = True
except SMTPHeloError as e:
print "Server did not reply"
except SMTPAuthenticationError as e:
print "Incorrect username/password combination"
except SMTPException as e:
print "Authentication failed"
if ServerConnect == True:
try:
smtp_server.sendmail(sender, receivers, msg.as_string())
print "Successfully sent email"
except SMTPException as e:
print "Error: unable to send email", e
finally:
smtp_server.close()
This should fix it:
Replace mail_me(cont,['xyz#xyzcom'])
with
mail_me(cont,'xyz#xyz.com')
The name comes from the FROM header. Refer to this answer please Specify a sender when sending mail with Python (smtplib)
A space is not a valid character in an email address. Special characters are only allowed in the external representation that shall be enclosed in double quotes. Additionaly, most SMTP servers actually use header rewriting to ensure that addresses are in standard format. As yours actually contains a space it is splitted and as it is not enclosed in quotes, the server address is appended to it.
You have just to replace msg['From'] = "XYZ ABC" with
msg['From'] = '"XYZ ABC"'
forcing inclusion of the address in double quotes.
import smtplib
from email.mime.text import MIMEText
def send_email(to=['example#example.com'], f_host='example.example.com', f_port=587, f_user='example#example.com', f_passwd='example-pass', subject='default subject', message='content message'):
smtpserver = smtplib.SMTP(f_host, f_port)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(f_user, f_passwd) # from email credential
msg = MIMEText(message, 'html')
msg['Subject'] = 'My custom Subject'
msg['From'] = "Admin"
msg['To'] = ','.join(to)
for t in to:
smtpserver.sendmail(f_user, t, msg.as_string()) # you just need to add this in for loop in your code.
smtpserver.close()
print('Mail is sent successfully!!')
cont = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the link you wanted.
</p>
</body>
</html>
"""
try:
send_email(message=cont)
except:
print('Mail could not be sent')
above method I have tried to send mail which is worked for me even I am able to send mail to my gmail account(in spam folder).
Let me know if you face any other related problem.
While the above methods are fine, a more explicit way is to make use of Address from email.headerregistry
The Address class takes 4 parameters:
(quoted from docs)
display_name - The display name portion of the address, if any, with all quoting removed. If the address does not have a display name, this attribute will be an empty string.
username - The username portion of the address, with all quoting removed.
domain - The domain portion of the address.
addr_spec - The username#domain portion of the address, correctly quoted for use as a bare address (the second form shown above). This attribute is not mutable.
import smtplib
from email.message import EmailMessage
from email.headerregistry import Address
msg = EmailMessage()
msg.set_content('Hello Stackoverflow!')
msg['Subject'] = 'SO'
msg['From'] = Address(display_name="Name", addr_spec="info#mydomain.com")
msg['To'] = "receiver#domain.com"
# Send the message via our own SMTP server.
server = smtplib.SMTP_SSL('smpt.gmail.net', 465) # place your own host
server.login("info#mydomain.com", "mypassword")
server.send_message(msg)
server.quit()

Sending email with color formatting in Python [duplicate]

This question already has answers here:
Send HTML emails with Python
(12 answers)
Closed 5 years ago.
I have the below Python code for sending an e-mail to my ID from the contents of file filename. I am trying to send the email with the text color-formatted.
Any ideas please advise.
def ps_Mail():
filename = "/tmp/ps_msg"
f = file(filename)
if os.path.exists(filename) and os.path.getsize(filename) > 0:
mailp = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
msg = MIMEMultipart('alternative')
msg['To'] = "karn#abc.com"
msg['Subject'] = "Uhh!! Unsafe rm process Seen"
msg['From'] = "psCheck#abc.com"
msg1 = MIMEText(f.read(), 'text')
msg.attach(msg1)
mailp.communicate(msg.as_string())
ps_Mail()
Here is the snippet I use to send HTML emails.
Please also read this
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = "my#email.com"
msg['To'] = "your#email.com"
text = "Hello World!"
html = """\
<html>
<head></head>
<body>
<p style="color: red;">Hello World!</p>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1) # text must be the first one
msg.attach(part2) # html must be the last one
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()

Categories