在这种情况下,您可以使用电子邮件包创建一条消息 -
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
msg = MIMEMultipart()
msg.attach(MIMEText(open("/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
更新2:附加PDF的最简单方式
要附加pdf
文件,请使用pdf
标志:
def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
from socket import gethostname
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import json
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
with open(password_path) as f:
config = json.load(f)
server.login('me@gmail.com', config['password'])
msg = MIMEMultipart()
message = f'{message}\nSend from Hostname: {gethostname()}'
msg['Subject'] = subject
msg['From'] = 'me@gmail.com'
msg['To'] = destination
msg.attach(MIMEText(message, "plain"))
with open(path_to_pdf, "rb") as f:
attach = MIMEApplication(f.read(),_subtype="pdf")
attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
msg.attach(attach)
server.send_message(msg)
致敬/鸣谢: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
email
模块,示例在http://docs.python.org/library/email-examples.html。 - Martijn Pieters