如何使用Python附件发送电子邮件? [英] How to send email with pdf attachment in Python?
本文介绍了如何使用Python附件发送电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
如何使用python发送电子邮件附件
我想编辑以下代码并发送带有附件的电子邮件。附件是一个pdf文件,它在/home/myuser/sample.pdf中,在linux环境中。下面应该怎么改?
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()
推荐答案
在这种情况下,您创建一封包含电子邮件包的消息 -
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()))
然后发送消息。
import smtplib
mailer = smtplib.SMTP()
mailer.connect()
mailer.sendmail(from_, to, msg.as_string())
mailer.close()
这里有几个例子 - http://docs.python.org/library/email-examples.html
Several examples here - http://docs.python.org/library/email-examples.html
这篇关于如何使用Python附件发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文