700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > pythonmail添加附件_Python SMTP 发送邮件并添加附件教程

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

时间:2023-05-13 20:24:34

相关推荐

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@' # 发送方邮箱

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

msg_to = '888888@' # 收件人邮箱

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("", 465) # 邮件服务器及端口号

s.login(msg_from, passwd)

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

except Exception as e:

print(str(e))

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。