Email using SMTP python from gmail account with html body - python

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

Related

how to send html and text mail with 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()

Python sending email with either plain text or html, but not both

I am experimenting with sending emails using Python. I have run into a problem where I cannot send plain text and html in the body, only one or the other. If I attach both parts, only the HTML shows up, and if I comment out the HTML part, then the plain text shows up.
I'm not sure why the email can't contain both. The code looks like this:
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username = 'email_address'
password = 'password'
def send_mail(text, subject, from_email, to_emails):
assert isinstance(to_emails, list)
msg = MIMEMultipart('alternative')
msg['From'] = from_email
msg['To'] = ', '.join(to_emails)
msg['Subject'] = subject
txt_part = MIMEText(text, 'plain')
msg.attach(txt_part)
html_part = MIMEText("<h1>This is working</h1>", 'html')
msg.attach(html_part)
msg_str = msg.as_string()
with smtplib.SMTP(host='smtp.gmail.com', port=587) as server:
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(from_email, to_emails, msg_str)
server.quit()
I actually believe according to 7.2 The Multipart Content-Type what you coded is correct and the email client chooses whichever it believes is "best" according to its capabilities, which generally is the HTML version . Using 'mixed' causes both versions to be displayed serially (assuming the capability exists). I have observed in Microsoft Outlook that the text version becomes an attachment.
To see both serially:
Instead of:
msg = MIMEMultipart('alternative')
use:
msg = MIMEMultipart('mixed')
The server.ehlo() command is superfluous.

Outlook stops working after running python email sending script?

I wrote a script to send an email using python. The script worked and the recipient received an email. However, I kept myself in CC and I didn't get an email and moreover, my outlook stopped working after that.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def success_email():
sender = 'abhishek_talwar#xyz.com'
recipients = 'GANA_PANGO#xyz.com'
CC = 'abhishek_talwar#xyz.com'
subject = "Load Balance Request Completed"
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
msg['CC'] = CC
# Create the body of the message (a plain-text and an HTML version).
text = 'Hi this is a test mail'
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text.encode('utf-8'), 'html')
# Attach parts into message container.
msg.attach(part1)
s = smtplib.SMTP('mail1.xyz.com')
x =s.sendmail(sender, recipients, msg.as_string())
print x
action = 'Success email sent for'
print action
success_email()
You're not sending the email to the CC list. You're adding the address in the head of the message, but not on the envelop.
x =s.sendmail(sender, [recipients, CC], msg.as_string())

Sending attachment in HTML email with Python

I saw there are a few somewhat similar questions on stack overflow already, but I couldn't find a solution to my specific problem in them.
I am trying to use Python to send an HTML email with a .pdf attachment. It seems to work fine when I check my email on gmail.com, but when I check the message through apple's Mail program, I do not see the attachment. Any idea what is causing this?
My code is below. A lot of it is copied from various places on stack overflow, so I do not completely understand what each part is doing, but it seems to (mostly) work:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from os.path import basename
import email
import email.mime.application
#plain text version
text = "This is the plain text version."
#html body
html = """<html><p>This is some HTML</p></html>"""
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Deliverability Report"
msg['From'] = "me#gmail.com"
msg['To'] = "you#gmail.com"
# Record the MIME types of both parts - text/plain and text/html
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# create PDF attachment
filename='graph.pdf'
fp=open(filename,'rb')
att = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
att.add_header('Content-Disposition','attachment',filename=filename)
# Attach parts into message container.
msg.attach(att)
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP()
s.connect('smtp.webfaction.com')
s.login('NAME','PASSWORD')
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
I'm not sure if it is relevant, but I am running this code on a WebFaction server.
Thanks for the help!
To have text, html and attachments at the same time it is necessary to use both mixed and alternative parts.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
text = "This is the plain text version."
html = "<html><p>This is some HTML</p></html>"
text_part = MIMEText(text, 'plain')
html_part = MIMEText(html, 'html')
msg_alternative = MIMEMultipart('alternative')
msg_alternative.attach(text_part)
msg_alternative.attach(html_part)
filename='graph.pdf'
fp=open(filename,'rb')
attachment = email.mime.application.MIMEApplication(fp.read(),_subtype="pdf")
fp.close()
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg_mixed = MIMEMultipart('mixed')
msg_mixed.attach(msg_alternative)
msg_mixed.attach(attachment)
msg_mixed['From'] = 'me#gmail.com'
msg_mixed['To'] = 'you#gmail.com'
msg_mixed['Subject'] = 'Deliverability Report'
smtp_obj = smtplib.SMTP('SERVER', port=25)
smtp_obj.ehlo()
smtp_obj.login('NAME', 'PASSWORD')
smtp_obj.sendmail(msg_mixed['From'], msg_mixed['To'], msg_mixed.as_string())
smtp_obj.quit()
Message structure should be like this:
Mixed:
Alternative:
Text
HTML
Attachment
Use
msg = MIMEMultipart('mixed')
instead of 'alternative'

Unable to send email from python

I am using the following code to send email from python program in localhost,
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "tonyr1291#gmail.com"
you = "testaccount#gmail.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
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)
s = smtplib.SMTP('localhost',5000)
s.sendmail(me, you, msg.as_string())
s.quit()
This code is from python documentation.
When I run this code, it is running continuously but no email is sent.
I would like to know, do I have to make some other configurations anywhere else other than this code.
I am not seeing any error.
I am using python 2.7
This is given as a solution in Sending HTML email using Python
It seems that you're using a gmail id. Now, the SMTP server is not your tornado server. it is the server of the email provider.
You can search online for the smtp settings for the gmail server and get the following:
Server name : smtp.gmail.com
Server port for SSL : 465
Server port for TLS : 587
I've gotten them from http://email.about.com/od/accessinggmail/f/Gmail_SMTP_Settings.htm
Also, you need to ensure you do not enable gmail's 2 step authentication when doing this, otherwise it will fail. Also, gmail specifically may require you to send other things like ehlo and starttls. You can find a previous answer with a complete example here : How to send an email with Gmail as provider using Python?
import smtplib
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"

Categories