How to send email with pdf attachment in Python? [

2020-02-04 21:22发布

Possible Duplicate:
How to send Email Attachments with python

I would like to edit the following code and send an email with an attachment. Attachment is a pdf file, it is under /home/myuser/sample.pdf, in linux environment. What should I change below?

import smtplib  
fromaddr = 'myemail@gmail.com'  
toaddrs  = 'youremail@gmail.com'  
msg = 'Hello'  


# Credentials (if needed)  
username = 'myemail'  
password = 'yyyyyy'  

# The actual mail send  
server = smtplib.SMTP('smtp.gmail.com:587')  
server.starttls()  
server.login(username,password)  
server.sendmail(fromaddr, toaddrs, msg)  
server.quit()  

2条回答
Bombasti
2楼-- · 2020-02-04 21:27

The recommended way is using Python's email module in order to compose a properly formatted MIME messages. See docs

For python 2
https://docs.python.org/2/library/email-examples.html

For python 3
https://docs.python.org/3/library/email.examples.html

查看更多
放荡不羁爱自由
3楼-- · 2020-02-04 21:33

You create a message with an email package in this case -

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(file("/home/myuser/sample.pdf").read()))

and then send the message.

import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()

Several examples here - http://docs.python.org/library/email-examples.html

UPDATE

Updating the link since the above yields a 404 https://docs.python.org/2/library/email-examples.html. Thanks @Tshirtman

查看更多
登录 后发表回答