Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send email attachments?

Tags:

python

email

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.

like image 301
Richard Avatar asked Jul 29 '10 12:07

Richard


People also ask

What do you write in an email when sending an attachment?

To write an e-mail message with an attachment having a formal tone, we can use “please refer to the attached file for your request” or “kindly see the attachment for details.” If the recipient isn't expecting the file, it is advisable to also quickly describe the content before writing the prompt.


2 Answers

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.

like image 193
Oli Avatar answered Sep 19 '22 01:09

Oli


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() 
like image 22
Ehsan Iran-Nejad Avatar answered Sep 18 '22 01:09

Ehsan Iran-Nejad