Related
I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the smtplib. Could someone please explain how to send an attachment in an email. I know there are other posts online but as a Python beginner I find them hard to understand.
Here's another:
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
def send_mail(send_from, send_to, subject, text, files=None,
server="127.0.0.1"):
assert isinstance(send_to, list)
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(f)
)
# After the file is closed
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
It's much the same as the first example... But it should be easier to drop in.
Here is the modified version from Oli for python 3
import smtplib
from pathlib import Path
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
def send_mail(send_from, send_to, subject, message, files=[],
server="localhost", port=587, username='', password='',
use_tls=True):
"""Compose and send email with provided info and attachments.
Args:
send_from (str): from name
send_to (list[str]): to name(s)
subject (str): message title
message (str): message body
files (list[str]): list of file paths to be attached to email
server (str): mail server host name
port (int): port number
username (str): server auth username
password (str): server auth password
use_tls (bool): use TLS mode
"""
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(message))
for path in files:
part = MIMEBase('application', "octet-stream")
with open(path, 'rb') as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename={}'.format(Path(path).name))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
if use_tls:
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
This is the code I ended up using:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
SUBJECT = "Email Data"
msg = MIMEMultipart()
msg['Subject'] = SUBJECT
msg['From'] = self.EMAIL_FROM
msg['To'] = ', '.join(self.EMAIL_TO)
part = MIMEBase('application', "octet-stream")
part.set_payload(open("text.txt", "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="text.txt"')
msg.attach(part)
server = smtplib.SMTP(self.EMAIL_SERVER)
server.sendmail(self.EMAIL_FROM, self.EMAIL_TO, msg.as_string())
Code is much the same as Oli's post.
Code based from Binary file email attachment problem post.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
msg = MIMEMultipart()
msg.attach(MIMEText(file("text.txt").read()))
msg.attach(MIMEImage(file("image.png").read()))
# to send
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()
Adapted from here.
Gmail version, working with Python 3.6 (note that you will need to change your Gmail settings to be able to send email via smtp from it:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from os.path import basename
def send_mail(send_from: str, subject: str, text: str,
send_to: list, files= None):
send_to= default_address if not send_to else send_to
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = ', '.join(send_to)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
ext = f.split('.')[-1:]
attachedfile = MIMEApplication(fil.read(), _subtype = ext)
attachedfile.add_header(
'content-disposition', 'attachment', filename=basename(f) )
msg.attach(attachedfile)
smtp = smtplib.SMTP(host="smtp.gmail.com", port= 587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
Usage:
username = 'my-address#gmail.com'
password = 'top-secret'
default_address = ['my-address2#gmail.com']
send_mail(send_from= username,
subject="test",
text="text",
send_to= None,
files= # pass a list with the full filepaths here...
)
To use with any other email provider, just change the smtp configurations.
Another way with python 3 (If someone is searching):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "sender mail address"
toaddr = "receiver mail address"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE EMAIL"
body = "TEXT YOU WANT TO SEND"
msg.attach(MIMEText(body, 'plain'))
filename = "fileName"
attachment = open("path of file", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "sender mail password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
Make sure to allow “less secure apps” on your Gmail account
Because there are many answers here for Python 3, but none which show how to use the overhauled email library from Python 3.6, here is a quick copy+paste from the current email examples documentation.
(I have abridged it somewhat to remove frills like guessing the correct MIME type.)
Modern code which targets Python >3.5 should no longer use the email.message.Message API (including the various MIMEText, MIMEMultipart, MIMEBase etc classes) or the even older mimetypes mumbo jumbo.
from email.message import EmailMessage
import smtplib
msg = EmailMessage()
msg["Subject"] = "Our family reunion"
msg["From"] = "me <sender#example.org>"
msg["To"] = "recipient <victim#example.net>"
# definitely don't mess with the .preamble
msg.set_content("Hello, victim! Look at these pictures")
with open("path/to/attachment.png", "rb") as fp:
msg.add_attachment(
fp.read(), maintype="image", subtype="png")
# Notice how smtplib now includes a send_message() method
with smtplib.SMTP("localhost") as s:
s.send_message(msg)
The modern email.message.EmailMessage API is now quite a bit more versatile and logical than the older version of the library. There are still a few kinks around the presentation in the documentation (it's not obvious how to change the Content-Disposition: of an attachment, for example; and the discussion of the policy module is probably too obscure for most newcomers) and fundamentally, you still need to have some sort of idea of what the MIME structure should look like (though the library now finally takes care of a lot of the nitty-gritty around that). Perhaps see What are the "parts" in a multipart email? for a brief introduction.
Using localhost as your SMTP server obviously only works if you actually have an SMTP server running on your local computer. Properly getting email off your system is a fairly complex separate question. For simple requirements, probably use your existing email account and your provider's email server (search for examples of using port 587 with Google, Yahoo, or whatever you have - what exactly works depends somewhat on the provider; some will only support port 465, or legacy port 25 which is however now by and large impossible to use on public-facing servers because of spam filtering).
The simplest code I could get to is:
#for attachment email
from django.core.mail import EmailMessage
def attachment_email(request):
email = EmailMessage(
'Hello', #subject
'Body goes here', #body
'MyEmail#MyEmail.com', #from
['SendTo#SendTo.com'], #to
['bcc#example.com'], #bcc
reply_to=['other#example.com'],
headers={'Message-ID': 'foo'},
)
email.attach_file('/my/path/file')
email.send()
It was based on the official Django documentation
Other answers are excellent, though I still wanted to share a different approach in case someone is looking for alternatives.
Main difference here is that using this approach you can use HTML/CSS to format your message, so you can get creative and give some styling to your email. Though you aren't enforced to use HTML, you can also still use only plain text.
Notice that this function accepts sending the email to multiple recipients and also allows to attach multiple files.
I've only tried this on Python 2, but I think it should work fine on 3 as well:
import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def send_email(subject, message, from_email, to_email=[], attachment=[]):
"""
:param subject: email subject
:param message: Body content of the email (string), can be HTML/CSS or plain text
:param from_email: Email address from where the email is sent
:param to_email: List of email recipients, example: ["a#a.com", "b#b.com"]
:param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
"""
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ", ".join(to_email)
msg.attach(MIMEText(message, 'html'))
for f in attachment:
with open(f, 'rb') as a_file:
basename = os.path.basename(f)
part = MIMEApplication(a_file.read(), Name=basename)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename
msg.attach(part)
email = smtplib.SMTP('your-smtp-host-name.com')
email.sendmail(from_email, to_email, msg.as_string())
I hope this helps! :-)
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import mimetypes
import email.mime.application
smtp_ssl_host = 'smtp.gmail.com' # smtp.mail.yahoo.com
smtp_ssl_port = 465
s = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
s.login(email_user, email_pass)
msg = MIMEMultipart()
msg['Subject'] = 'I have a picture'
msg['From'] = email_user
msg['To'] = email_user
txt = MIMEText('I just bought a new camera.')
msg.attach(txt)
filename = 'introduction-to-algorithms-3rd-edition-sep-2010.pdf' #path to file
fo=open(filename,'rb')
attach = email.mime.application.MIMEApplication(fo.read(),_subtype="pdf")
fo.close()
attach.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(attach)
s.send_message(msg)
s.quit()
For explanation, you can use this link it explains properly
https://medium.com/#sdoshi579/to-send-an-email-along-with-attachment-using-smtp-7852e77623
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
import smtplib
msg = MIMEMultipart()
password = "password"
msg['From'] = "from_address"
msg['To'] = "to_address"
msg['Subject'] = "Attached Photo"
msg.attach(MIMEImage(file("abc.jpg").read()))
file = "file path"
fp = open(file, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
I know this is an old question but I thought there must be an easier way of doing this than the other examples, thus I made a library that solves this cleanly without polluting your codebase. Including attachments is super easy:
from redmail import EmailSender
from pathlib import Path
# Configure an email sender
email = EmailSender(
host="<SMTP HOST>", port=0,
user_name="me#example.com", password="<PASSWORD>"
)
# Send an email
email.send(
sender="me#example.com",
receivers=["you#example.com"],
subject="An example email"
attachments={
"myfile.txt": Path("path/to/a_file.txt"),
"myfile.html": "<h1>Content of a HTML attachment</h1>"
}
)
You may also directly attach bytes, a Pandas DataFrame (which is converted to format depending on file extension in the key), a Matplotlib Figure or a Pillow Image. The library is most likely all the features you need for an email sender (has a lot more than attachments).
To install:
pip install redmail
Use it any way you like. I also wrote extensive documentation: https://red-mail.readthedocs.io/en/latest/
None of the currently given answers here will work correctly with non-ASCII symbols in filenames with clients like GMail, Outlook 2016, and others that don't support RFC 2231 (e.g., see here). The Python 3 code below is adapted from some other stackoverflow answers (sorry, didn't save the origin links) and odoo/openerp code for Python 2.7 (see ir_mail_server.py). It works correctly with GMail and others, and also uses SSL.
import smtplib, ssl
from os.path import basename
from email.mime.base import MIMEBase
from mimetypes import guess_type
from email.encoders import encode_base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.charset import Charset
def try_coerce_ascii(string_utf8):
"""Attempts to decode the given utf8-encoded string
as ASCII after coercing it to UTF-8, then return
the confirmed 7-bit ASCII string.
If the process fails (because the string
contains non-ASCII characters) returns ``None``.
"""
try:
string_utf8.encode('ascii')
except UnicodeEncodeError:
return
return string_utf8
def encode_header_param(param_text):
"""Returns an appropriate RFC 2047 encoded representation of the given
header parameter value, suitable for direct assignation as the
param value (e.g. via Message.set_param() or Message.add_header())
RFC 2822 assumes that headers contain only 7-bit characters,
so we ensure it is the case, using RFC 2047 encoding when needed.
:param param_text: unicode or utf-8 encoded string with header value
:rtype: string
:return: if ``param_text`` represents a plain ASCII string,
return the same 7-bit string, otherwise returns an
ASCII string containing the RFC2047 encoded text.
"""
if not param_text: return ""
param_text_ascii = try_coerce_ascii(param_text)
return param_text_ascii if param_text_ascii\
else Charset('utf8').header_encode(param_text)
smtp_server = '<someserver.com>'
smtp_port = 465 # Default port for SSL
sender_email = '<sender_email#some.com>'
sender_password = '<PASSWORD>'
receiver_emails = ['<receiver_email_1#some.com>', '<receiver_email_2#some.com>']
subject = 'Test message'
message = """\
Hello! This is a test message with attachments.
This message is sent from Python."""
files = ['<path1>/файл1.pdf', '<path2>/файл2.png']
# Create a secure SSL context
context = ssl.create_default_context()
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = COMMASPACE.join(receiver_emails)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(message))
for f in files:
mimetype, _ = guess_type(f)
mimetype = mimetype.split('/', 1)
with open(f, "rb") as fil:
part = MIMEBase(mimetype[0], mimetype[1])
part.set_payload(fil.read())
encode_base64(part)
filename_rfc2047 = encode_header_param(basename(f))
# The default RFC 2231 encoding of Message.add_header() works in Thunderbird but not GMail
# so we fix it by using RFC 2047 encoding for the filename instead.
part.set_param('name', filename_rfc2047)
part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047)
msg.attach(part)
with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_emails, msg.as_string())
Here is an updated version for Python 3.6 and newer using the EmailMessage class of the overhauled email module in the Python standard library.
import mimetypes
import os
import smtplib
from email.message import EmailMessage
username = "user#example.com"
password = "password"
smtp_url = "smtp.example.com"
port = 587
def send_mail(subject: str, send_from: str, send_to: str, message: str, directory: str, filename: str):
# Create the email message
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = send_from
msg['To'] = send_to
# Set email content
msg.set_content(message)
path = directory + filename
if os.path.exists(path):
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
# Add email attachment
with open(path, 'rb') as fp:
msg.add_attachment(fp.read(),
maintype=maintype,
subtype=subtype,
filename=filename)
smtp = smtplib.SMTP(smtp_url, port)
smtp.starttls() # for using port 587
smtp.login(username, password)
smtp.send_message(msg)
smtp.quit()
You can find more examples here.
Below is combination of what I've found from SoccerPlayer's post Here and the following link that made it easier for me to attach an xlsx file. Found Here
file = 'File.xlsx'
username=''
password=''
send_from = ''
send_to = 'recipient1 , recipient2'
Cc = 'recipient'
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Cc'] = Cc
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = ''
server = smtplib.SMTP('smtp.gmail.com')
port = '587'
fp = open(file, 'rb')
part = MIMEBase('application','vnd.ms-excel')
part.set_payload(fp.read())
fp.close()
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename='Name File Here')
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(',') + msg['Cc'].split(','), msg.as_string())
smtp.quit()
You can also specify the type of attachment you want in your e-mail, as an example I used pdf:
def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
from socket import gethostname
#import email
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import json
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
with open(password_path) as f:
config = json.load(f)
server.login('me#gmail.com', config['password'])
# Craft message (obj)
msg = MIMEMultipart()
message = f'{message}\nSend from Hostname: {gethostname()}'
msg['Subject'] = subject
msg['From'] = 'me#gmail.com'
msg['To'] = destination
# Insert the text to the msg going by e-mail
msg.attach(MIMEText(message, "plain"))
# Attach the pdf to the msg going by e-mail
with open(path_to_pdf, "rb") as f:
#attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
attach = MIMEApplication(f.read(),_subtype="pdf")
attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
msg.attach(attach)
# send msg
server.send_message(msg)
inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
Try This i hope this might help
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "youremailhere"
toaddr = input("Enter The Email Adress You want to send to: ")
# instance of MIMEMultipart
msg = MIMEMultipart()
# storing the senders email address
msg['From'] = fromaddr
# storing the receivers email address
msg['To'] = toaddr
# storing the subject
msg['Subject'] = input("What is the Subject:\t")
# string to store the body of the mail
body = input("What is the body:\t")
# attach the body with the msg instance
msg.attach(MIMEText(body, 'plain'))
# open the file to be sent
filename = input("filename:")
attachment = open(filename, "rb")
# instance of MIMEBase and named as p
p = MIMEBase('application', 'octet-stream')
# To change the payload into encoded form
p.set_payload((attachment).read())
# encode into base64
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
# attach the instance 'p' to instance 'msg'
msg.attach(p)
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login(fromaddr, "yourpaswordhere)
# Converts the Multipart msg into a string
text = msg.as_string()
# sending the mail
s.sendmail(fromaddr, toaddr, text)
# terminating the session
s.quit()
Had a bit of a hussle in getting my script to send generic attachments but after a bit of work doing research and skimming through articles on this post, I finally came up with the following
# to query:
import sys
import ast
from datetime import datetime
import smtplib
import mimetypes
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from dotenv import load_dotenv, dotenv_values
load_dotenv() # load environment variables from .env
'''
sample .env file
# .env file
SECRET_KEY="gnhfpsjxxxxxxxx"
DOMAIN="GMAIL"
TOP_LEVEL_DOMAIN="COM"
EMAIL="CHESERExxxxxx#${DOMAIN}.${TOP_LEVEL_DOMAIN}"
TO_ADDRESS = ("cheseremxxxxx#gmail.com","cheserek#gmail.com")#didn't use this in the code but you can load recipients from here
'''
import smtplib
tls_port = 587
ssl_port = 465
smtp_server_domain_names = {'GMAIL': ('smtp.gmail.com', tls_port, ssl_port),
'OUTLOOK': ('smtp-mail.outlook.com', tls_port, ssl_port),
'YAHOO': ('smtp.mail.yahoo.com', tls_port, ssl_port),
'AT&T': ('smtp.mail.att.net', tls_port, ssl_port),
}
# todo: Ability to choose mail server provider
# auto read in from the dictionary the respective mail server address and the tls and ssl ports
class Bimail:
def __init__(self, subject, recipients):
self.subject = subject
self.recipients = recipients
self.htmlbody = ''
self.mail_username = 'will be loaded from .env file'
self.mail_password = 'loaded from .env file as well'
self.attachments = []
# Creating an smtp object
# todo: if gmail passed in use gmail's dictionary values
def setup_mail_client(self, domain_key_to_use="GMAIL",
email_servers_domains_dict=smtp_server_domain_names):
"""
:param report_pdf:
:type to_address: str
"""
smtpObj = None
encryption_status = True
config = dotenv_values(".env")
# check if the domain_key exists from within the available email-servers-domains dict file passed in
# else throw an error
# read environment file to get the Domain to be used
if f"{domain_key_to_use}" in email_servers_domains_dict.keys():
# if the key is found do the following
# 1.extract the domain,tls,ssl ports from email_servers dict for use in program
try:
values_tuple = email_servers_domains_dict.get(f"{domain_key_to_use}")
ssl_port = values_tuple[2]
tls_port = values_tuple[1]
smtp_server = values_tuple[0]
smtpObj = smtplib.SMTP(smtp_server, tls_port)
print(f"Success connect with tls on {tls_port}")
print('Awaiting for connection encryption via startttls()')
encryption_status = False
except:
print(f"Failed connection via tls on port {tls_port}")
try:
smtpObj = smtplib.SMTP_SSL(smtp_server, ssl_port)
print(f"Success connect with ssl on {ssl_port}")
encryption_status = True
except:
print(f"Failed connection via ssl on port {ssl_port}")
finally:
print("Within Finally block")
if not smtpObj:
print("Failed!!! no Internet connection")
else:
# if connection channel is unencrypted via the use of tls encrypt it
if not encryption_status:
status = smtpObj.starttls()
if status[0] == 220:
print("Successfully Encrypted tls channel")
print("Successfully Connected!!!! Requesting Login")
# Loading .env file values to config variable
#load Login Creds from ENV File
self.mail_username = f'{config.get("EMAIL")}'
self.mail_password = f'{cofig.get("SECRET_KEY")}'
status = smtpObj.login(self.mail_usernam,self.mail_password)
if status[0] == 235:
print("Successfully Authenticated User to xxx account")
success = self.send(smtpObj, f'{config.get("EMAIL")}')
if not bool(success):
print(f"Success in Sending Mail to {success}")
print("Disconnecting from Server INstance")
quit_result = smtpObj.quit()
else:
print(f"Failed to Post {success}!!!")
print(f"Quiting anyway !!!")
quit_result = smtpObj.quit()
else:
print("Application Specific Password is Required")
else:
print("World")
def send(self,smtpObj,from_address):
msg = MIMEMultipart('alternative')
msg['From'] = from_address
msg['Subject'] = self.subject
msg['To'] = ", ".join(self.recipients) # to must be array of the form ['mailsender135#gmail.com']
msg.preamble = "preamble goes here"
# check if there are attachments if yes, add them
if self.attachments:
self.attach(msg)
# add html body after attachments
msg.attach(MIMEText(self.htmlbody, 'html'))
# send
print(f"Attempting Email send to the following addresses {self.recipients}")
result = smtpObj.sendmail(from_address, self.recipients,msg.as_string())
return result
def htmladd(self, html):
self.htmlbody = self.htmlbody + '<p></p>' + html
def attach(self, msg):
for f in self.attachments:
ctype, encoding = mimetypes.guess_type(f)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
if maintype == "text":
fp = open(f)
# Note: we should handle calculating the charset
attachment = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "image":
fp = open(f, "rb")
attachment = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "ppt":
fp = open(f, "rb")
attachment = MIMEApplication(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "audio":
fp = open(f, "rb")
attachment = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(f, "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=f)
attachment.add_header('Content-ID', '<{}>'.format(f))
msg.attach(attachment)
def addattach(self, files):
self.attachments = self.attachments + files
# example below
if __name__ == '__main__':
# subject and recipients
mymail = Bimail('Sales email ' + datetime.now().strftime('%Y/%m/%d'),
['cheseremxx#gmail.com', 'tkemboxxx#gmail.com'])
# start html body. Here we add a greeting.
mymail.htmladd('Good morning, find the daily summary below.')
# Further things added to body are separated by a paragraph, so you do not need to worry about newlines for new sentences
# here we add a line of text and an html table previously stored in the variable
mymail.htmladd('Daily sales')
mymail.addattach(['htmlsalestable.xlsx'])
# another table name + table
mymail.htmladd('Daily bestsellers')
mymail.addattach(['htmlbestsellertable.xlsx'])
# add image chart title
mymail.htmladd('Weekly sales chart')
# attach image chart
mymail.addattach(['saleschartweekly.png'])
# refer to image chart in html
mymail.htmladd('<img src="cid:saleschartweekly.png"/>')
# attach another file
mymail.addattach(['MailSend.py'])
# send!
mymail.setup_mail_client( domain_key_to_use="GMAIL",email_servers_domains_dict=smtp_server_domain_names)
With my code you can send email attachments using gmail you will need to:
Set your gmail address at ___YOUR SMTP EMAIL HERE___
Set your gmail account password at __YOUR SMTP PASSWORD HERE___
In the ___EMAIL TO RECEIVE THE MESSAGE__ part you need to set the destination email address.
Alarm notification is the subject.
Someone has entered the room, picture attached is the body.
["/home/pi/webcam.jpg"] is an image attachment.
Here is the full code:
#!/usr/bin/env python
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
USERNAME = "___YOUR SMTP EMAIL HERE___"
PASSWORD = "__YOUR SMTP PASSWORD HERE___"
def sendMail(to, subject, text, files=[]):
assert type(to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = USERNAME
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo_or_helo_if_needed()
server.starttls()
server.ehlo_or_helo_if_needed()
server.login(USERNAME,PASSWORD)
server.sendmail(USERNAME, to, msg.as_string())
server.quit()
sendMail( ["___EMAIL TO RECEIVE THE MESSAGE__"],
"Alarm notification",
"Someone has entered the room, picture attached",
["/home/pi/webcam.jpg"] )
I am using python to generate and send email messages. I want the messages to include both
embedded images (this post shows how)
attachments
Currently, the code below does all of this, except that the attachments are not 100% showing up. In Outlook, there is no way to see them. In Gmail, when you see the mail in your inbox it seems to have no attachment, but when you open the mail, there is the attachment at the bottom.
How can I get the attachments to show up consistently?
Following is my current code.
I'll also show below that a comparison between the header seem from my gmail inbox of an email sent with this, vs one where everything works as expected.
import smtplib
from os import getcwd, path
from config import mailer_settings
from email.message import EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.utils import formatdate
from mimetypes import guess_type
def send_mail(send_from, send_to, subject, message, message_html="", file_loc: str = None, locs=[], cids=[],
use_tls=True):
"""Compose and send email with provided info and attachments.
Args:
send_from (str): from name
send_to (list[str]): to name(s)
subject (str): message title
message (str): message body
message_html: message body with html
file_loc (list[str]): path of file to be attached to email
locs: list[str]: list of file locations for embedded images
cids: list: list of generated (email.utils.make_msgid) cids for embedded images
use_tls (bool): use TLS mode
"""
# --- Method 1: can't get embedded pictures to work ---
# msg = MIMEMultipart('alternative')
# part1 = MIMEText(message, 'plain')
# part2 = MIMEText(message_html, 'html')
# msg.attach(part1)
# msg.attach(part2)
# --- Method 2 currently best ---
msg = EmailMessage()
msg.set_content(message)
msg.add_alternative(message_html, subtype='html')
# --- Method 3:
# from (https://stackoverflow.com/questions/35925969/python-sent-mime-email-attachments-not-showing-up-in-mail-live)
# not sure how to get it to work with embedded pictures, since MIMEImage is now deprecated ---
# Create the root message and fill in the from, to, and subject headers
b = False
if b:
msg = MIMEMultipart('related')
msg.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
# We reference the image in the IMG SRC attribute by the ID we give it below
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
msgAlternative.attach(msgText)
# This example assumes the image is in the current directory
fp = open(getcwd() + '\\mail\\example_pdf.ong', 'rb')
# :( MIMEImage is deprecated
# msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
# msgImage.add_header('Content-ID', '<image1>')
# msg.attach(msgImage)
# --- end Method 3 ---
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
# now open the image and attach it to the email
for loc, cid in zip(locs, cids):
with open(loc, 'rb') as img:
# know the Content-Type of the image
maintype, subtype = guess_type(img.name)[0].split('/')
# attach it
msg.get_payload()[1].add_related(img.read(), maintype=maintype, subtype=subtype, cid=cid)
if file_loc:
mimetype, encoding = guess_type(file_loc)
mimetype = mimetype.split('/', 1)
fp = open(file_loc, 'rb')
attachment = MIMEBase(mimetype[0], mimetype[1])
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment',
filename=path.basename(file_loc))
msg.attach(attachment)
server = mailer_settings["server"]
port = mailer_settings["port"]
username = mailer_settings["username"]
password = mailer_settings["password"]
smtp = smtplib.SMTP(server, port)
if use_tls:
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(send_from, send_to, msg.as_string())
print("message sent!")
smtp.quit()
The Header in my emails:
--===============0780945104962264622==
Content-Type: application/pdf
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Ecoemballage - test_product_01a.pdf"
--===============0780945104962264622==--
Header from a Microsoft email that is showing it attachment like it should:
--=-FabH5jV6gYAblpCdlHoDfQ==
Content-Type: application/octet-stream; name=221885190882013.pdf
Content-Disposition: attachment; filename=221885190882013.pdf
Content-Transfer-Encoding: base64
--=-FabH5jV6gYAblpCdlHoDfQ==--
I found the answer here.
The problem here is that you have directly attached a pre-built MIME
part to a multipart/alternative message. It ends in an incorrect
message that may be poorly processed by mail readers.
In the email.message interface, you should use the add_attachement
method. It will handle the base64 encoding and will change the message
into a multipart/mixed one:
To fix, I changed my code as follows:
if file_loc:
fp = open(file_loc, 'rb')
filename = path.basename(file_loc)
# mimetype, encoding = guess_type(file_loc)
# mimetype = mimetype.split('/', 1)
# attachment = MIMEBase(mimetype[0], mimetype[1])
# attachment.set_payload(fp.read())
# fp.close()
# encoders.encode_base64(attachment)
# attachment.add_header('Content-Disposition', 'attachment',
# filename=path.basename(file_loc))
# msg.attach(attachment)
msg.add_attachment(fp.read(), maintype='application',
subtype='octet-stream', filename=filename)
I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the smtplib. Could someone please explain how to send an attachment in an email. I know there are other posts online but as a Python beginner I find them hard to understand.
Here's another:
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
def send_mail(send_from, send_to, subject, text, files=None,
server="127.0.0.1"):
assert isinstance(send_to, list)
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(f)
)
# After the file is closed
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
It's much the same as the first example... But it should be easier to drop in.
Here is the modified version from Oli for python 3
import smtplib
from pathlib import Path
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
def send_mail(send_from, send_to, subject, message, files=[],
server="localhost", port=587, username='', password='',
use_tls=True):
"""Compose and send email with provided info and attachments.
Args:
send_from (str): from name
send_to (list[str]): to name(s)
subject (str): message title
message (str): message body
files (list[str]): list of file paths to be attached to email
server (str): mail server host name
port (int): port number
username (str): server auth username
password (str): server auth password
use_tls (bool): use TLS mode
"""
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(message))
for path in files:
part = MIMEBase('application', "octet-stream")
with open(path, 'rb') as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename={}'.format(Path(path).name))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
if use_tls:
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
This is the code I ended up using:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
SUBJECT = "Email Data"
msg = MIMEMultipart()
msg['Subject'] = SUBJECT
msg['From'] = self.EMAIL_FROM
msg['To'] = ', '.join(self.EMAIL_TO)
part = MIMEBase('application', "octet-stream")
part.set_payload(open("text.txt", "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="text.txt"')
msg.attach(part)
server = smtplib.SMTP(self.EMAIL_SERVER)
server.sendmail(self.EMAIL_FROM, self.EMAIL_TO, msg.as_string())
Code is much the same as Oli's post.
Code based from Binary file email attachment problem post.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import smtplib
msg = MIMEMultipart()
msg.attach(MIMEText(file("text.txt").read()))
msg.attach(MIMEImage(file("image.png").read()))
# to send
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()
Adapted from here.
Gmail version, working with Python 3.6 (note that you will need to change your Gmail settings to be able to send email via smtp from it:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from os.path import basename
def send_mail(send_from: str, subject: str, text: str,
send_to: list, files= None):
send_to= default_address if not send_to else send_to
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = ', '.join(send_to)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
ext = f.split('.')[-1:]
attachedfile = MIMEApplication(fil.read(), _subtype = ext)
attachedfile.add_header(
'content-disposition', 'attachment', filename=basename(f) )
msg.attach(attachedfile)
smtp = smtplib.SMTP(host="smtp.gmail.com", port= 587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
Usage:
username = 'my-address#gmail.com'
password = 'top-secret'
default_address = ['my-address2#gmail.com']
send_mail(send_from= username,
subject="test",
text="text",
send_to= None,
files= # pass a list with the full filepaths here...
)
To use with any other email provider, just change the smtp configurations.
Another way with python 3 (If someone is searching):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "sender mail address"
toaddr = "receiver mail address"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE EMAIL"
body = "TEXT YOU WANT TO SEND"
msg.attach(MIMEText(body, 'plain'))
filename = "fileName"
attachment = open("path of file", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "sender mail password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
Make sure to allow “less secure apps” on your Gmail account
Because there are many answers here for Python 3, but none which show how to use the overhauled email library from Python 3.6, here is a quick copy+paste from the current email examples documentation.
(I have abridged it somewhat to remove frills like guessing the correct MIME type.)
Modern code which targets Python >3.5 should no longer use the email.message.Message API (including the various MIMEText, MIMEMultipart, MIMEBase etc classes) or the even older mimetypes mumbo jumbo.
from email.message import EmailMessage
import smtplib
msg = EmailMessage()
msg["Subject"] = "Our family reunion"
msg["From"] = "me <sender#example.org>"
msg["To"] = "recipient <victim#example.net>"
# definitely don't mess with the .preamble
msg.set_content("Hello, victim! Look at these pictures")
with open("path/to/attachment.png", "rb") as fp:
msg.add_attachment(
fp.read(), maintype="image", subtype="png")
# Notice how smtplib now includes a send_message() method
with smtplib.SMTP("localhost") as s:
s.send_message(msg)
The modern email.message.EmailMessage API is now quite a bit more versatile and logical than the older version of the library. There are still a few kinks around the presentation in the documentation (it's not obvious how to change the Content-Disposition: of an attachment, for example; and the discussion of the policy module is probably too obscure for most newcomers) and fundamentally, you still need to have some sort of idea of what the MIME structure should look like (though the library now finally takes care of a lot of the nitty-gritty around that). Perhaps see What are the "parts" in a multipart email? for a brief introduction.
Using localhost as your SMTP server obviously only works if you actually have an SMTP server running on your local computer. Properly getting email off your system is a fairly complex separate question. For simple requirements, probably use your existing email account and your provider's email server (search for examples of using port 587 with Google, Yahoo, or whatever you have - what exactly works depends somewhat on the provider; some will only support port 465, or legacy port 25 which is however now by and large impossible to use on public-facing servers because of spam filtering).
The simplest code I could get to is:
#for attachment email
from django.core.mail import EmailMessage
def attachment_email(request):
email = EmailMessage(
'Hello', #subject
'Body goes here', #body
'MyEmail#MyEmail.com', #from
['SendTo#SendTo.com'], #to
['bcc#example.com'], #bcc
reply_to=['other#example.com'],
headers={'Message-ID': 'foo'},
)
email.attach_file('/my/path/file')
email.send()
It was based on the official Django documentation
Other answers are excellent, though I still wanted to share a different approach in case someone is looking for alternatives.
Main difference here is that using this approach you can use HTML/CSS to format your message, so you can get creative and give some styling to your email. Though you aren't enforced to use HTML, you can also still use only plain text.
Notice that this function accepts sending the email to multiple recipients and also allows to attach multiple files.
I've only tried this on Python 2, but I think it should work fine on 3 as well:
import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def send_email(subject, message, from_email, to_email=[], attachment=[]):
"""
:param subject: email subject
:param message: Body content of the email (string), can be HTML/CSS or plain text
:param from_email: Email address from where the email is sent
:param to_email: List of email recipients, example: ["a#a.com", "b#b.com"]
:param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
"""
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ", ".join(to_email)
msg.attach(MIMEText(message, 'html'))
for f in attachment:
with open(f, 'rb') as a_file:
basename = os.path.basename(f)
part = MIMEApplication(a_file.read(), Name=basename)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename
msg.attach(part)
email = smtplib.SMTP('your-smtp-host-name.com')
email.sendmail(from_email, to_email, msg.as_string())
I hope this helps! :-)
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import mimetypes
import email.mime.application
smtp_ssl_host = 'smtp.gmail.com' # smtp.mail.yahoo.com
smtp_ssl_port = 465
s = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
s.login(email_user, email_pass)
msg = MIMEMultipart()
msg['Subject'] = 'I have a picture'
msg['From'] = email_user
msg['To'] = email_user
txt = MIMEText('I just bought a new camera.')
msg.attach(txt)
filename = 'introduction-to-algorithms-3rd-edition-sep-2010.pdf' #path to file
fo=open(filename,'rb')
attach = email.mime.application.MIMEApplication(fo.read(),_subtype="pdf")
fo.close()
attach.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(attach)
s.send_message(msg)
s.quit()
For explanation, you can use this link it explains properly
https://medium.com/#sdoshi579/to-send-an-email-along-with-attachment-using-smtp-7852e77623
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
import smtplib
msg = MIMEMultipart()
password = "password"
msg['From'] = "from_address"
msg['To'] = "to_address"
msg['Subject'] = "Attached Photo"
msg.attach(MIMEImage(file("abc.jpg").read()))
file = "file path"
fp = open(file, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
I know this is an old question but I thought there must be an easier way of doing this than the other examples, thus I made a library that solves this cleanly without polluting your codebase. Including attachments is super easy:
from redmail import EmailSender
from pathlib import Path
# Configure an email sender
email = EmailSender(
host="<SMTP HOST>", port=0,
user_name="me#example.com", password="<PASSWORD>"
)
# Send an email
email.send(
sender="me#example.com",
receivers=["you#example.com"],
subject="An example email"
attachments={
"myfile.txt": Path("path/to/a_file.txt"),
"myfile.html": "<h1>Content of a HTML attachment</h1>"
}
)
You may also directly attach bytes, a Pandas DataFrame (which is converted to format depending on file extension in the key), a Matplotlib Figure or a Pillow Image. The library is most likely all the features you need for an email sender (has a lot more than attachments).
To install:
pip install redmail
Use it any way you like. I also wrote extensive documentation: https://red-mail.readthedocs.io/en/latest/
None of the currently given answers here will work correctly with non-ASCII symbols in filenames with clients like GMail, Outlook 2016, and others that don't support RFC 2231 (e.g., see here). The Python 3 code below is adapted from some other stackoverflow answers (sorry, didn't save the origin links) and odoo/openerp code for Python 2.7 (see ir_mail_server.py). It works correctly with GMail and others, and also uses SSL.
import smtplib, ssl
from os.path import basename
from email.mime.base import MIMEBase
from mimetypes import guess_type
from email.encoders import encode_base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.charset import Charset
def try_coerce_ascii(string_utf8):
"""Attempts to decode the given utf8-encoded string
as ASCII after coercing it to UTF-8, then return
the confirmed 7-bit ASCII string.
If the process fails (because the string
contains non-ASCII characters) returns ``None``.
"""
try:
string_utf8.encode('ascii')
except UnicodeEncodeError:
return
return string_utf8
def encode_header_param(param_text):
"""Returns an appropriate RFC 2047 encoded representation of the given
header parameter value, suitable for direct assignation as the
param value (e.g. via Message.set_param() or Message.add_header())
RFC 2822 assumes that headers contain only 7-bit characters,
so we ensure it is the case, using RFC 2047 encoding when needed.
:param param_text: unicode or utf-8 encoded string with header value
:rtype: string
:return: if ``param_text`` represents a plain ASCII string,
return the same 7-bit string, otherwise returns an
ASCII string containing the RFC2047 encoded text.
"""
if not param_text: return ""
param_text_ascii = try_coerce_ascii(param_text)
return param_text_ascii if param_text_ascii\
else Charset('utf8').header_encode(param_text)
smtp_server = '<someserver.com>'
smtp_port = 465 # Default port for SSL
sender_email = '<sender_email#some.com>'
sender_password = '<PASSWORD>'
receiver_emails = ['<receiver_email_1#some.com>', '<receiver_email_2#some.com>']
subject = 'Test message'
message = """\
Hello! This is a test message with attachments.
This message is sent from Python."""
files = ['<path1>/файл1.pdf', '<path2>/файл2.png']
# Create a secure SSL context
context = ssl.create_default_context()
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = COMMASPACE.join(receiver_emails)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(message))
for f in files:
mimetype, _ = guess_type(f)
mimetype = mimetype.split('/', 1)
with open(f, "rb") as fil:
part = MIMEBase(mimetype[0], mimetype[1])
part.set_payload(fil.read())
encode_base64(part)
filename_rfc2047 = encode_header_param(basename(f))
# The default RFC 2231 encoding of Message.add_header() works in Thunderbird but not GMail
# so we fix it by using RFC 2047 encoding for the filename instead.
part.set_param('name', filename_rfc2047)
part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047)
msg.attach(part)
with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_emails, msg.as_string())
Here is an updated version for Python 3.6 and newer using the EmailMessage class of the overhauled email module in the Python standard library.
import mimetypes
import os
import smtplib
from email.message import EmailMessage
username = "user#example.com"
password = "password"
smtp_url = "smtp.example.com"
port = 587
def send_mail(subject: str, send_from: str, send_to: str, message: str, directory: str, filename: str):
# Create the email message
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = send_from
msg['To'] = send_to
# Set email content
msg.set_content(message)
path = directory + filename
if os.path.exists(path):
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
# Add email attachment
with open(path, 'rb') as fp:
msg.add_attachment(fp.read(),
maintype=maintype,
subtype=subtype,
filename=filename)
smtp = smtplib.SMTP(smtp_url, port)
smtp.starttls() # for using port 587
smtp.login(username, password)
smtp.send_message(msg)
smtp.quit()
You can find more examples here.
Below is combination of what I've found from SoccerPlayer's post Here and the following link that made it easier for me to attach an xlsx file. Found Here
file = 'File.xlsx'
username=''
password=''
send_from = ''
send_to = 'recipient1 , recipient2'
Cc = 'recipient'
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Cc'] = Cc
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = ''
server = smtplib.SMTP('smtp.gmail.com')
port = '587'
fp = open(file, 'rb')
part = MIMEBase('application','vnd.ms-excel')
part.set_payload(fp.read())
fp.close()
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename='Name File Here')
msg.attach(part)
smtp = smtplib.SMTP('smtp.gmail.com')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(',') + msg['Cc'].split(','), msg.as_string())
smtp.quit()
You can also specify the type of attachment you want in your e-mail, as an example I used pdf:
def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
from socket import gethostname
#import email
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import json
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
with open(password_path) as f:
config = json.load(f)
server.login('me#gmail.com', config['password'])
# Craft message (obj)
msg = MIMEMultipart()
message = f'{message}\nSend from Hostname: {gethostname()}'
msg['Subject'] = subject
msg['From'] = 'me#gmail.com'
msg['To'] = destination
# Insert the text to the msg going by e-mail
msg.attach(MIMEText(message, "plain"))
# Attach the pdf to the msg going by e-mail
with open(path_to_pdf, "rb") as f:
#attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
attach = MIMEApplication(f.read(),_subtype="pdf")
attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
msg.attach(attach)
# send msg
server.send_message(msg)
inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
Try This i hope this might help
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "youremailhere"
toaddr = input("Enter The Email Adress You want to send to: ")
# instance of MIMEMultipart
msg = MIMEMultipart()
# storing the senders email address
msg['From'] = fromaddr
# storing the receivers email address
msg['To'] = toaddr
# storing the subject
msg['Subject'] = input("What is the Subject:\t")
# string to store the body of the mail
body = input("What is the body:\t")
# attach the body with the msg instance
msg.attach(MIMEText(body, 'plain'))
# open the file to be sent
filename = input("filename:")
attachment = open(filename, "rb")
# instance of MIMEBase and named as p
p = MIMEBase('application', 'octet-stream')
# To change the payload into encoded form
p.set_payload((attachment).read())
# encode into base64
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
# attach the instance 'p' to instance 'msg'
msg.attach(p)
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login(fromaddr, "yourpaswordhere)
# Converts the Multipart msg into a string
text = msg.as_string()
# sending the mail
s.sendmail(fromaddr, toaddr, text)
# terminating the session
s.quit()
Had a bit of a hussle in getting my script to send generic attachments but after a bit of work doing research and skimming through articles on this post, I finally came up with the following
# to query:
import sys
import ast
from datetime import datetime
import smtplib
import mimetypes
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from dotenv import load_dotenv, dotenv_values
load_dotenv() # load environment variables from .env
'''
sample .env file
# .env file
SECRET_KEY="gnhfpsjxxxxxxxx"
DOMAIN="GMAIL"
TOP_LEVEL_DOMAIN="COM"
EMAIL="CHESERExxxxxx#${DOMAIN}.${TOP_LEVEL_DOMAIN}"
TO_ADDRESS = ("cheseremxxxxx#gmail.com","cheserek#gmail.com")#didn't use this in the code but you can load recipients from here
'''
import smtplib
tls_port = 587
ssl_port = 465
smtp_server_domain_names = {'GMAIL': ('smtp.gmail.com', tls_port, ssl_port),
'OUTLOOK': ('smtp-mail.outlook.com', tls_port, ssl_port),
'YAHOO': ('smtp.mail.yahoo.com', tls_port, ssl_port),
'AT&T': ('smtp.mail.att.net', tls_port, ssl_port),
}
# todo: Ability to choose mail server provider
# auto read in from the dictionary the respective mail server address and the tls and ssl ports
class Bimail:
def __init__(self, subject, recipients):
self.subject = subject
self.recipients = recipients
self.htmlbody = ''
self.mail_username = 'will be loaded from .env file'
self.mail_password = 'loaded from .env file as well'
self.attachments = []
# Creating an smtp object
# todo: if gmail passed in use gmail's dictionary values
def setup_mail_client(self, domain_key_to_use="GMAIL",
email_servers_domains_dict=smtp_server_domain_names):
"""
:param report_pdf:
:type to_address: str
"""
smtpObj = None
encryption_status = True
config = dotenv_values(".env")
# check if the domain_key exists from within the available email-servers-domains dict file passed in
# else throw an error
# read environment file to get the Domain to be used
if f"{domain_key_to_use}" in email_servers_domains_dict.keys():
# if the key is found do the following
# 1.extract the domain,tls,ssl ports from email_servers dict for use in program
try:
values_tuple = email_servers_domains_dict.get(f"{domain_key_to_use}")
ssl_port = values_tuple[2]
tls_port = values_tuple[1]
smtp_server = values_tuple[0]
smtpObj = smtplib.SMTP(smtp_server, tls_port)
print(f"Success connect with tls on {tls_port}")
print('Awaiting for connection encryption via startttls()')
encryption_status = False
except:
print(f"Failed connection via tls on port {tls_port}")
try:
smtpObj = smtplib.SMTP_SSL(smtp_server, ssl_port)
print(f"Success connect with ssl on {ssl_port}")
encryption_status = True
except:
print(f"Failed connection via ssl on port {ssl_port}")
finally:
print("Within Finally block")
if not smtpObj:
print("Failed!!! no Internet connection")
else:
# if connection channel is unencrypted via the use of tls encrypt it
if not encryption_status:
status = smtpObj.starttls()
if status[0] == 220:
print("Successfully Encrypted tls channel")
print("Successfully Connected!!!! Requesting Login")
# Loading .env file values to config variable
#load Login Creds from ENV File
self.mail_username = f'{config.get("EMAIL")}'
self.mail_password = f'{cofig.get("SECRET_KEY")}'
status = smtpObj.login(self.mail_usernam,self.mail_password)
if status[0] == 235:
print("Successfully Authenticated User to xxx account")
success = self.send(smtpObj, f'{config.get("EMAIL")}')
if not bool(success):
print(f"Success in Sending Mail to {success}")
print("Disconnecting from Server INstance")
quit_result = smtpObj.quit()
else:
print(f"Failed to Post {success}!!!")
print(f"Quiting anyway !!!")
quit_result = smtpObj.quit()
else:
print("Application Specific Password is Required")
else:
print("World")
def send(self,smtpObj,from_address):
msg = MIMEMultipart('alternative')
msg['From'] = from_address
msg['Subject'] = self.subject
msg['To'] = ", ".join(self.recipients) # to must be array of the form ['mailsender135#gmail.com']
msg.preamble = "preamble goes here"
# check if there are attachments if yes, add them
if self.attachments:
self.attach(msg)
# add html body after attachments
msg.attach(MIMEText(self.htmlbody, 'html'))
# send
print(f"Attempting Email send to the following addresses {self.recipients}")
result = smtpObj.sendmail(from_address, self.recipients,msg.as_string())
return result
def htmladd(self, html):
self.htmlbody = self.htmlbody + '<p></p>' + html
def attach(self, msg):
for f in self.attachments:
ctype, encoding = mimetypes.guess_type(f)
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
if maintype == "text":
fp = open(f)
# Note: we should handle calculating the charset
attachment = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "image":
fp = open(f, "rb")
attachment = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "ppt":
fp = open(f, "rb")
attachment = MIMEApplication(fp.read(), _subtype=subtype)
fp.close()
elif maintype == "audio":
fp = open(f, "rb")
attachment = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(f, "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=f)
attachment.add_header('Content-ID', '<{}>'.format(f))
msg.attach(attachment)
def addattach(self, files):
self.attachments = self.attachments + files
# example below
if __name__ == '__main__':
# subject and recipients
mymail = Bimail('Sales email ' + datetime.now().strftime('%Y/%m/%d'),
['cheseremxx#gmail.com', 'tkemboxxx#gmail.com'])
# start html body. Here we add a greeting.
mymail.htmladd('Good morning, find the daily summary below.')
# Further things added to body are separated by a paragraph, so you do not need to worry about newlines for new sentences
# here we add a line of text and an html table previously stored in the variable
mymail.htmladd('Daily sales')
mymail.addattach(['htmlsalestable.xlsx'])
# another table name + table
mymail.htmladd('Daily bestsellers')
mymail.addattach(['htmlbestsellertable.xlsx'])
# add image chart title
mymail.htmladd('Weekly sales chart')
# attach image chart
mymail.addattach(['saleschartweekly.png'])
# refer to image chart in html
mymail.htmladd('<img src="cid:saleschartweekly.png"/>')
# attach another file
mymail.addattach(['MailSend.py'])
# send!
mymail.setup_mail_client( domain_key_to_use="GMAIL",email_servers_domains_dict=smtp_server_domain_names)
With my code you can send email attachments using gmail you will need to:
Set your gmail address at ___YOUR SMTP EMAIL HERE___
Set your gmail account password at __YOUR SMTP PASSWORD HERE___
In the ___EMAIL TO RECEIVE THE MESSAGE__ part you need to set the destination email address.
Alarm notification is the subject.
Someone has entered the room, picture attached is the body.
["/home/pi/webcam.jpg"] is an image attachment.
Here is the full code:
#!/usr/bin/env python
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
USERNAME = "___YOUR SMTP EMAIL HERE___"
PASSWORD = "__YOUR SMTP PASSWORD HERE___"
def sendMail(to, subject, text, files=[]):
assert type(to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = USERNAME
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo_or_helo_if_needed()
server.starttls()
server.ehlo_or_helo_if_needed()
server.login(USERNAME,PASSWORD)
server.sendmail(USERNAME, to, msg.as_string())
server.quit()
sendMail( ["___EMAIL TO RECEIVE THE MESSAGE__"],
"Alarm notification",
"Someone has entered the room, picture attached",
["/home/pi/webcam.jpg"] )
I am following this example on their website:
https://developers.google.com/gmail/api/guides/sending
basically, I want to use create_message_with_attachment() and send_message() to send my email. Below is what I got so far:
#send our spreadsheet
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from apiclient import errors
from googleapiclient import http
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import io
import mimetypes
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import base64
def create_message_with_attachment(
sender, to, subject, message_text, file):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
file: The path to the file to be attached.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEMultipart()
message['to'] = to
message['from'] = sender
message['subject'] = subject
msg = MIMEText(message_text)
message.attach(msg)
content_type, encoding = mimetypes.guess_type(file)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, sub_type = content_type.split('/', 1)
fp = open(file, 'rb')
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
fp.close()
filename = os.path.basename(file)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
message.attach(msg)
return {'raw': base64.urlsafe_b64encode(message.as_string())}
#return {'raw': base64.urlsafe_b64encode(message.as_bytes())}
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print('Message Id: %s' % message['id'])
return message
except errors.HttpError as error:
print('An error occurred: %s' % error)
def main(mail_service,spreadsheetId,new_invoice_filename):
print('We are emailing the spreadsheet.')
sender = 'me'
to = 'me'
subject = 'test '+new_filename
message_text = 'Hi sdf \n P '
attachment = 'D:/My Documents/file.pdf'
msg = create_message_with_attachment(sender, to, subject, message_text, attachment)
send_message(mail_service, sender, msg)
so in the documentation, it says create_message_with_attachment will specifically return the raw field, but when I send the message with send_message(), I don't see how I can put the raw I got in there.
So I am really confused.
Thanks
How can I send an image attachment using boto3 SES send_email client?
I know that I can use send_raw_email to send an attachment but I need to send the message body with html data. If this is not possible, how can I send an email with html data using boto3.ses.send_raw_email() ?
After going through several sources, including other SO questions, blogs and Python documentation, I came up with the code below.
Allows for text and/or html emails and attachments.
Separated the MIME and boto3 parts, in case you want to re-use MIME for other purposes, like sending an email with a SMTP client, instead of boto3.
import os
import boto3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def create_multipart_message(
sender: str, recipients: list, title: str, text: str=None, html: str=None, attachments: list=None)\
-> MIMEMultipart:
"""
Creates a MIME multipart message object.
Uses only the Python `email` standard library.
Emails, both sender and recipients, can be just the email string or have the format 'The Name <the_email#host.com>'.
:param sender: The sender.
:param recipients: List of recipients. Needs to be a list, even if only one recipient.
:param title: The title of the email.
:param text: The text version of the email body (optional).
:param html: The html version of the email body (optional).
:param attachments: List of files to attach in the email.
:return: A `MIMEMultipart` to be used to send the email.
"""
multipart_content_subtype = 'alternative' if text and html else 'mixed'
msg = MIMEMultipart(multipart_content_subtype)
msg['Subject'] = title
msg['From'] = sender
msg['To'] = ', '.join(recipients)
# Record the MIME types of both parts - text/plain and text/html.
# According to RFC 2046, the last part of a multipart message, in this case the HTML message, is best and preferred.
if text:
part = MIMEText(text, 'plain')
msg.attach(part)
if html:
part = MIMEText(html, 'html')
msg.attach(part)
# Add attachments
for attachment in attachments or []:
with open(attachment, 'rb') as f:
part = MIMEApplication(f.read())
part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))
msg.attach(part)
return msg
def send_mail(
sender: str, recipients: list, title: str, text: str=None, html: str=None, attachments: list=None) -> dict:
"""
Send email to recipients. Sends one mail to all recipients.
The sender needs to be a verified email in SES.
"""
msg = create_multipart_message(sender, recipients, title, text, html, attachments)
ses_client = boto3.client('ses') # Use your settings here
return ses_client.send_raw_email(
Source=sender,
Destinations=recipients,
RawMessage={'Data': msg.as_string()}
)
if __name__ == '__main__':
sender_ = 'The Sender <the_sender#email.com>'
recipients_ = ['Recipient One <recipient_1#email.com>', 'recipient_2#email.com']
title_ = 'Email title here'
text_ = 'The text version\nwith multiple lines.'
body_ = """<html><head></head><body><h1>A header 1</h1><br>Some text."""
attachments_ = ['/path/to/file1/filename1.txt', '/path/to/file2/filename2.txt']
response_ = send_mail(sender_, recipients_, title_, text_, body_, attachments_)
print(response_)
March 2019
Here is a copy-pasted solution from the UPDATED official documentation (https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html):
import os
import boto3
from botocore.exceptions import ClientError
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# Replace sender#example.com with your "From" address.
# This address must be verified with Amazon SES.
SENDER = "Sender Name <sender#example.com>"
# Replace recipient#example.com with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = "recipient#example.com"
# Specify a configuration set. If you do not want to use a configuration
# set, comment the following variable, and the
# ConfigurationSetName=CONFIGURATION_SET argument below.
CONFIGURATION_SET = "ConfigSet"
# If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
AWS_REGION = "us-west-2"
# The subject line for the email.
SUBJECT = "Customer service contact info"
# The full path to the file that will be attached to the email.
ATTACHMENT = "path/to/customers-to-contact.xlsx"
# The email body for recipients with non-HTML email clients.
BODY_TEXT = "Hello,\r\nPlease see the attached file for a list of customers to contact."
# The HTML body of the email.
BODY_HTML = """\
<html>
<head></head>
<body>
<h1>Hello!</h1>
<p>Please see the attached file for a list of customers to contact.</p>
</body>
</html>
"""
# The character encoding for the email.
CHARSET = "utf-8"
# Create a new SES resource and specify a region.
client = boto3.client('ses',region_name=AWS_REGION)
# Create a multipart/mixed parent container.
msg = MIMEMultipart('mixed')
# Add subject, from and to lines.
msg['Subject'] = SUBJECT
msg['From'] = SENDER
msg['To'] = RECIPIENT
# Create a multipart/alternative child container.
msg_body = MIMEMultipart('alternative')
# Encode the text and HTML content and set the character encoding. This step is
# necessary if you're sending a message with characters outside the ASCII range.
textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)
# Add the text and HTML parts to the child container.
msg_body.attach(textpart)
msg_body.attach(htmlpart)
# Define the attachment part and encode it using MIMEApplication.
att = MIMEApplication(open(ATTACHMENT, 'rb').read())
# Add a header to tell the email client to treat this part as an attachment,
# and to give the attachment a name.
att.add_header('Content-Disposition','attachment',filename=os.path.basename(ATTACHMENT))
# Attach the multipart/alternative child container to the multipart/mixed
# parent container.
msg.attach(msg_body)
# Add the attachment to the parent container.
msg.attach(att)
#print(msg)
try:
#Provide the contents of the email.
response = client.send_raw_email(
Source=SENDER,
Destinations=[
RECIPIENT
],
RawMessage={
'Data':msg.as_string(),
},
ConfigurationSetName=CONFIGURATION_SET
)
# Display an error if something goes wrong.
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message ID:"),
print(response['MessageId'])
To expand upon #adkl's answer, Amazon's own example is using older Python way of handling emails and attachments. Nothing wrong with that, just that current documentation on those modules is not comprehensive and might be confusing for new users like me.
Here's simple example on forming message with CSV attachment.
from email.message import EmailMessage
def create_email_message(sender: str, recipients: list, title: str, text: str,
attachment: BytesIO, file_name: str) -> EmailMessage:
msg = EmailMessage()
msg["Subject"] = title
msg['From'] = sender
msg['To'] = ', '.join(recipients)
msg.set_content(text)
data = attachment.read()
msg.add_attachment(
data,
maintype="text",
subtype="csv",
filename=file_name
)
return msg
# Client init, attachment file creation here
message = create_email_message(...)
try:
ses.send_raw_email(
Source=sender,
Destinations=recipients,
RawMessage={'Data': message.as_string()}
)
except ClientError as e:
logger.exception(f"Cannot send email report to {recipients}: {e}")
else:
logger.info("Sent report successfully")
In this example I use BytesIO object as a source for attachment, but you can use any file-like object that supports read() method.
Shameless copy example from "HOW TO SEND HTML MAILS USING AMAZON SES "
This is how a typical email data content looks like.
message_dict = { 'Data':
'From: ' + mail_sender + '\n'
'To: ' + mail_receivers_list + '\n'
'Subject: ' + mail_subject + '\n'
'MIME-Version: 1.0\n'
'Content-Type: text/html;\n\n' +
mail_content}
If you want to send attachment and HTML text using boto3.ses.send_raw_email, you just need use above message dict and pass. (just put your html text under the mail_content)
response = client.send_raw_email(
Destinations=[
],
FromArn='',
RawMessage=message_dict,
ReturnPathArn='',
Source='',
SourceArn='',
)
In fact, the raw attachment header should works in both send_email() and send_raw_email() . Except in send_mail, you should put the attachment inside Text, not html.
This worked for me to send an attachment:
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import boto.ses
AWS_ACCESS_KEY = 'HEREYOURACCESSKEY'
AWS_SECRET_KEY = 'HEREYOURSECRETKEY'
class Email(object):
def __init__(self, to, subject):
self.to = to
self.subject = subject
self.text = None
self.attachment = None
def text(self, text):
self.text = text
def add_attachment(self, attachment):
self.attachment = attachment
def send(self, from_addr=None, file_name = None):
connection = boto.ses.connect_to_region(
'us-east-1',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY
)
msg = MIMEMultipart()
msg['Subject'] = self.subject
msg['From'] = from_addr
msg['To'] = self.to
part = MIMEApplication(self.attachment)
part.add_header('Content-Disposition', 'attachment', filename=file_name)
part.add_header('Content-Type', 'application/vnd.ms-excel; charset=UTF-8')
msg.attach(part)
# the message body
part = MIMEText(self.text)
msg.attach(part)
return connection.send_raw_email(msg.as_string(),source=from_addr,destinations=self.to)
if __name__ == "__main__":
email = Email(to='toMail#gmail.com', subject='Your subject!')
email.text('This is a text body.')
#you could use StringIO.StringIO() to get the file value
email.add_attachment(yourFileValue)
email.send(from_addr='from#mail.com',file_name="yourFile.txt")
Here's the class I ended up using. Drop into a Lambda file and use it.
Accepts a list of filenames for attachments. Sends HTML email. Changes \n for <br />
I saved the below class [1] as emailer.py and use as:
from emailer import Emailer
def lambda_handler(event, context):
# ...
emailer = Emailer()
emailer.send(
to=email_recipients_list,
subject=subject_string,
fromx=from_address_string,
body=email_body_string,
attachments=attachments_list
)
[1]
import boto3
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
class Emailer(object):
""" send email with attachments """
def send(self, to, subject, fromx, body=None, content=None, attachments=None):
""" sends email with attachments
Parameters:
* to (list or comma separated string of addresses): recipient(s) address
* fromx (string): from address of email
* body (string, optional): Body of email ('\n' are converted to '< br/>')
* content (string, optional): Body of email specified as filename
* attachments (list, optional): list of paths of files to attach
"""
if attachments is None:
attachments = []
self.to = to
self.subject = subject
self.fromx = fromx
self.attachment = None
self.body = body
self.content = content
self.attachments = attachments
if type(self.to) is list:
self.to = ",".join(self.to)
message = MIMEMultipart()
message['Subject'] = self.subject
message['From'] = self.fromx
message['To'] = self.to
if self.content and os.path.isfile(self.content):
part = MIMEText(open(str(self.content)).read().replace("\n", "<br />"), "html")
message.attach(part)
elif self.body:
part = MIMEText(self.body.replace("\\n", "<br />").replace("\n", "<br />"), "html")
message.attach(part)
for attachment in self.attachments:
part = MIMEApplication(open(attachment, 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=attachment.split("/")[-1])
message.attach(part)
ses = boto3.client('ses', region_name='us-east-1')
response = ses.send_raw_email(
Source=message['From'],
Destinations=message['To'].split(","),
RawMessage={
'Data': message.as_string()
}
)
This can also be implemented using python version 2.7.x
Following is the working code for this--
[Note - The 'sender' and 'recipients' that you add must be verified in AWS SES. OR SES must be moved from 'sandbox' state to 'Production' state
import os
import boto3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def create_multipart_message(email_metadata):
sender = email_metadata['sender_']
recipients = email_metadata['recipients_']
title = email_metadata['title_']
text = email_metadata['text_']
html = email_metadata['body_']
attachments = email_metadata['attachments_']
multipart_content_subtype = 'alternative' if text and html else 'mixed'
msg = MIMEMultipart(multipart_content_subtype)
msg['Subject'] = title
msg['From'] = sender
msg['To'] = ', '.join(recipients)
# Record the MIME types of both parts - text/plain and text/html.
# According to RFC 2046, the last part of a multipart message, in this case the HTML message, is best and preferred.
if text:
part = MIMEText(text, 'plain')
msg.attach(part)
if html:
part = MIMEText(html, 'html')
msg.attach(part)
# Add attachments
for attachment in attachments or []:
with open(attachment, 'rb') as f:
part = MIMEApplication(f.read())
part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))
msg.attach(part)
return msg
def send_mail(email_metadata):
#sender: str, recipients: list, title: str, text: str=None, html: str=None, attachments: list=None) -> dict:
"""
Send email to recipients. Sends one mail to all recipients.
The sender needs to be a verified email in SES.
"""
msg = create_multipart_message(email_metadata)
ses_client = boto3.client('ses') # Use your settings here
return ses_client.send_raw_email(
Source=email_metadata['sender_'],
Destinations=email_metadata['recipients_'],
RawMessage={'Data': msg.as_string()}
)
if __name__ == '__main__':
email_metadata = {
"sender_" : "The Sender <the_sender#email.com>",
"recipients_" : ['Recipient One <recipient_1#email.com>','Recipient two <recipient_2#email.com>'],
"title_" : "Email title here",
"text_" : "The text version\nwith multiple lines.",
"body_" : "<html><head></head><body><h1>A header 1</h1><br>Some text.",
"attachments_" : ['/path/to/file1/filename1.txt','/path/to/file2/filename2.txt']
}
response_ = send_mail(email_metadata)
print(response_)