三味线
三味线
Published on 2020-04-27 / 43 Visits
0
0

Python发送邮件

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 第三方 SMTP 服务
mail_host = "smtp.163.com"       # 设置服务器
mail_port = 25                   # 端口
mail_user = "xxxxxxxxx@163.com"  # 用户名
mail_passwd = "xxxxxxxxxxxx"     # 密码
# 发件人
mail_from = "某组织<xxxxxxx@163.com>"
# 收件人
receivers = ['xxxxxx@qq.com']
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header(mail_from, 'utf-8')
message['To'] = ','.join(receivers)
# 标题
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
# 发送附件 test.txt 文件
# attach = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
# attach["Content-Type"] = 'application/octet-stream'
# attach["Content-Disposition"] = 'attachment; filename="test.txt"'
# message.attach(attach)
try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, mail_port)
    smtpObj.login(mail_user, mail_passwd)
    smtpObj.sendmail(mail_user, receivers, message.as_string())
    print("Send mail success.")
except smtplib.SMTPException:
    print("Error: Send mail failed.")


Comment