温馨提示×

python收发邮件功能怎么实现

小亿
83
2023-10-13 02:43:31
栏目: 编程语言

要实现Python的收发邮件功能,可以使用Python的内置模块smtplib和email。

首先,你需要导入这两个模块:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

接下来,你需要设置发送方和接收方的邮箱信息:

# 发件人邮箱
sender = 'sender@example.com'
# 收件人邮箱
receivers = ['receiver1@example.com', 'receiver2@example.com']

然后,你需要创建邮件内容和邮件对象:

# 创建一个带附件的邮件对象
message = MIMEMultipart()
message['From'] = Header("发件人名称", 'utf-8')
message['To'] = Header("收件人名称", 'utf-8')
message['Subject'] = Header("邮件标题", 'utf-8')
# 邮件正文内容
message.attach(MIMEText('邮件正文', 'plain', 'utf-8'))
# 附件内容
att = MIMEText(open('附件文件路径', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="附件文件名"'
message.attach(att)

接下来,你需要登录发件人邮箱服务器,并发送邮件:

try:
smtpObj = smtplib.SMTP('smtp.example.com', 25)
smtpObj.login('发件人邮箱用户名', '发件人邮箱密码')
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")

以上代码中的一些信息,比如发件人邮箱、收件人邮箱、发件人邮箱用户名、发件人邮箱密码等都需要根据实际情况进行替换。

注意:在发送邮件之前,请确保你已经安装了Python的smtplib和email模块,你可以使用pip install smtplib email命令来进行安装。

0