How to send an email with Python? How to send an email with Python? python python

How to send an email with Python?


I recommend that you use the standard packages email and smtplib together to send email. Please look at the following example (reproduced from the Python documentation). Notice that if you follow this approach, the "simple" task is indeed simple, and the more complex tasks (like attaching binary objects or sending plain/HTML multipart messages) are accomplished very rapidly.

# Import smtplib for the actual sending functionimport smtplib# Import the email modules we'll needfrom email.mime.text import MIMEText# Open a plain text file for reading.  For this example, assume that# the text file contains only ASCII characters.with open(textfile, 'rb') as fp:    # Create a text/plain message    msg = MIMEText(fp.read())# me == the sender's email address# you == the recipient's email addressmsg['Subject'] = 'The contents of %s' % textfilemsg['From'] = memsg['To'] = you# Send the message via our own SMTP server, but don't include the# envelope header.s = smtplib.SMTP('localhost')s.sendmail(me, [you], msg.as_string())s.quit()

For sending email to multiple destinations, you can also follow the example in the Python documentation:

# Import smtplib for the actual sending functionimport smtplib# Here are the email package modules we'll needfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipart# Create the container (outer) email message.msg = MIMEMultipart()msg['Subject'] = 'Our family reunion'# me == the sender's email address# family = the list of all recipients' email addressesmsg['From'] = memsg['To'] = ', '.join(family)msg.preamble = 'Our family reunion'# Assume we know that the image files are all in PNG formatfor file in pngfiles:    # Open the files in binary mode.  Let the MIMEImage class automatically    # guess the specific image type.    with open(file, 'rb') as fp:        img = MIMEImage(fp.read())    msg.attach(img)# Send the email via our own SMTP server.s = smtplib.SMTP('localhost')s.sendmail(me, family, msg.as_string())s.quit()

As you can see, the header To in the MIMEText object must be a string consisting of email addresses separated by commas. On the other hand, the second argument to the sendmail function must be a list of strings (each string is an email address).

So, if you have three email addresses: person1@example.com, person2@example.com, and person3@example.com, you can do as follows (obvious sections omitted):

to = ["person1@example.com", "person2@example.com", "person3@example.com"]msg['To'] = ",".join(to)s.sendmail(me, to, msg.as_string())

the ",".join(to) part makes a single string out of the list, separated by commas.

From your questions I gather that you have not gone through the Python tutorial - it is a MUST if you want to get anywhere in Python - the documentation is mostly excellent for the standard library.


Well, you want to have an answer that is up-to-date and modern.

Here is my answer:

When I need to mail in Python, I use the mailgun API wich get's a lot of the headaches with sending mails sorted out. They have a wonderfull app/api that allows you to send 5,000 free emails per month.

Sending an email would be like this:

def send_simple_message():    return requests.post(        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",        auth=("api", "YOUR_API_KEY"),        data={"from": "Excited User <mailgun@YOUR_DOMAIN_NAME>",              "to": ["bar@example.com", "YOU@YOUR_DOMAIN_NAME"],              "subject": "Hello",              "text": "Testing some Mailgun awesomness!"})

You can also track events and lots more, see the quickstart guide.

I hope you find this useful!


I'd like to help you with sending emails by advising the yagmail package (I'm the maintainer, sorry for the advertising, but I feel it can really help!).

The whole code for you would be:

import yagmailyag = yagmail.SMTP(FROM, 'pass')yag.send(TO, SUBJECT, TEXT)

Note that I provide defaults for all arguments, for example if you want to send to yourself, you can omit TO, if you don't want a subject, you can omit it also.

Furthermore, the goal is also to make it really easy to attach html code or images (and other files).

Where you put contents you can do something like:

contents = ['Body text, and here is an embedded image:', 'http://somedomain/image.png',            'You can also find an audio file attached.', '/local/path/song.mp3']

Wow, how easy it is to send attachments! This would take like 20 lines without yagmail ;)

Also, if you set it up once, you'll never have to enter the password again (and have it safely stored). In your case you can do something like:

import yagmailyagmail.SMTP().send(contents = contents)

which is much more concise!

I'd invite you to have a look at the github or install it directly with pip install yagmail.