Question
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.
How-To
Here's another, adapted from here:
- 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)
- )
- 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()
沒有留言:
張貼留言