pythonmail添加附件_Python SMTP 发送邮件并添加附件教程

之前老王介绍过《PHP 使用 SMTP 发送邮件教程(PEAR Mail 包)》,这次需求是用 Python 调用 SMTP 服务发送邮件,并且需要在邮件中添加附件(文本文件),本文分享下具体的代码。

一、准备工作

1、SMTP 邮箱

2、添加包依赖

主要用到了 2 个 Python 自带的包,其中 smtplib 就是 Python SMTP 功能必用包:

import smtplib

from email.mime.text import MIMEText

二、源码分享

以下代码就是 Python3 调用 QQ 邮箱的 SMTP 发送邮件的源码,在发送的邮件内容中添加了一个附件:

def send_email(content, attach_file):

msg_from = '8888888@qq.com' # 发送方邮箱

passwd = 'tjvoskdjsklkcaij' # 填入发送方邮箱的授权码

msg_to = '888888@gmail.com' # 收件人邮箱

subject = "The Subject"

msg = MIMEMultipart()

msg.attach(MIMEText(content, 'plain', 'utf-8'))

msg['Subject'] = subject

msg['From'] = msg_from

msg['To'] = msg_to

# 构造附件1,传送当前目录下的 attach_file 文件

att1 = MIMEText(open(attach_file, 'rb').read(), 'base64', 'utf-8')

att1["Content-Type"] = 'application/octet-stream'

# 这里的 filename 可以任意写,写什么名字,邮件中显示什么名字

att1["Content-Disposition"] = 'attachment; filename="diff.html"'

msg.attach(att1)

try:

s = smtplib.SMTP_SSL("smtp.qq.com", 465) # 邮件服务器及端口号

s.login(msg_from, passwd)

s.sendmail(msg_from, msg_to, msg.as_string())

except Exception as e:

print(str(e))


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部