Skip to content

Instantly share code, notes, and snippets.

@rdempsey
Created December 6, 2014 21:30
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save rdempsey/22afd43f8d777b78ef22 to your computer and use it in GitHub Desktop.
Save rdempsey/22afd43f8d777b78ef22 to your computer and use it in GitHub Desktop.
Use Python 3 to send an email with an attachment using Gmail
#!/usr/bin/env python
# encoding: utf-8
"""
python_3_email_with_attachment.py
Created by Robert Dempsey on 12/6/14.
Copyright (c) 2014 Robert Dempsey. Use at your own peril.
This script works with Python 3.x
NOTE: replace values in ALL CAPS with your own values
"""
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
def main():
sender = 'YOUR GMAIL ADDRESS'
gmail_password = 'YOUR GMAIL PASSWORD'
recipients = ['EMAIL ADDRESSES HERE SEPARATED BY COMMAS']
# Create the enclosing (outer) message
outer = MIMEMultipart()
outer['Subject'] = 'EMAIL SUBJECT'
outer['To'] = COMMASPACE.join(recipients)
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
# List of attachments
attachments = ['FULL PATH TO ATTACHMENTS HERE']
# Add the attachments to the message
for file in attachments:
try:
with open(file, 'rb') as fp:
msg = MIMEBase('application', "octet-stream")
msg.set_payload(fp.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
outer.attach(msg)
except:
print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
raise
composed = outer.as_string()
# Send the email
try:
with smtplib.SMTP('smtp.gmail.com', 587) as s:
s.ehlo()
s.starttls()
s.ehlo()
s.login(sender, gmail_password)
s.sendmail(sender, recipients, composed)
s.close()
print("Email sent!")
except:
print("Unable to send the email. Error: ", sys.exc_info()[0])
raise
if __name__ == '__main__':
main()
@mlape
Copy link

mlape commented Nov 7, 2015

How would one add a message to this email?

@summer-liu
Copy link

from email.mime.text import MIMEText

text = "EMAIL MESSAGE"
outer.attach(
MIMEText(text, 'plain')) # or 'html'

@ZeevBB
Copy link

ZeevBB commented Sep 30, 2017

Thank you. Works nicely

@Rkauff
Copy link

Rkauff commented Dec 28, 2017

This is great! Can I suggest adding "Import Sys" at the top?

@adityaridha
Copy link

Hi, I tried to follow your code to send html file, it successfully sent but when i open the file in browser it become messy yet the html format is the same as the original. Do you know what is the issue ?

Thank you in advance

@karanchawda95
Copy link

I also have the same problem as of adityaridha. Any help asap would be appreciated. Thanks in advance.

@aishenghuomeidaoli
Copy link

good job

@shadabshaukat
Copy link

Can i upload this script to my blog and give you credit for the script with a back link ?

@SoaQa
Copy link

SoaQa commented Nov 21, 2018

thank you!

@renesax14
Copy link

does this work for sending pdfs too?

@martinig94
Copy link

does this work for sending pdfs too?

Yep. it does

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment