如何在Python中发送带有pdf附件的电子邮件?

2024-06-28 11:05:25 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
How to send Email Attachments with python

我想编辑以下代码并发送一封带有附件的电子邮件。附件是一个pdf文件,位于linux环境下的/home/myuser/sample.pdf下。下面我该换什么?

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()  

Tags: comsend附件serverpdfusernamemsgpassword
2条回答

推荐的方法是使用Python的email模块来正确地组合 格式化的MIME消息。参见文档

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

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

在这种情况下,您可以使用电子邮件包创建邮件-

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()))

然后发送消息。

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

这里有几个例子-http://docs.python.org/library/email-examples.html

更新

更新链接,因为上面的结果是404 https://docs.python.org/2/library/email-examples.html。谢谢@Tshirtman

相关问题 更多 >