栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

在这种情况下,您使用电子邮件包创建了一条消息-

from email.MIMEMultipart import MIMEMultipartfrom email.MIMEText import MIMETextfrom email.MIMEImage import MIMEImagemsg = MIMEMultipart()msg.attach(MIMEText(open("/home/myuser/sample.pdf").read()))

然后发送消息。

import smtplibmailer = 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


Update2:附加pdf的最简单方法

附加

pdf
使用pdf标志:

def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):    ## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script    from socket import gethostname    #import email    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'])        # Craft message (obj)        msg = MIMEMultipart()        message = f'{message}nSend from Hostname: {gethostname()}'        msg['Subject'] = subject        msg['From'] = 'me@gmail.com'        msg['To'] = destination        # Insert the text to the msg going by e-mail        msg.attach(MIMEText(message, "plain"))        # Attach the pdf to the msg going by e-mail        with open(path_to_pdf, "rb") as f: #attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf") attach = MIMEApplication(f.read(),_subtype="pdf")        attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))        msg.attach(attach)        # send msg        server.send_message(msg)

灵感/来源:http : //linuxcursor.com/python-
programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-
script



转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/640092.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号