Python 发送电子邮件

zhangpan 2020-01-10

首先创建一个包含邮箱地址、密码、收件人的字典

import smtplib
from email.mime.text import MIMEText
from email.header import Header
email = {‘sender‘: ‘*****@126.com‘,       ‘password‘: ‘***‘,        ‘recipient‘: [***‘,‘***@qq.com‘]}
smtpServer =‘smtp.126.com‘
smtpObj = smtplib.SMTP(smtpServer, 25)  # 创建一个 SMTP 对象,连接到邮箱服务器
smtpObj.ehlo()          # 向 SMTP 电子邮件服务器打招呼
smtpObj.starttls()      # 为连接实现加密

username = email[‘sender‘]
password = email[‘password‘]      # 密码
smtpObj.login(username, password) # 登录到 SMTP 服务器

sender = username
recipient = ‘,‘.join(email[‘recipient‘]) # 如果不是群发就不必用 join

subject = ‘python 发送邮件‘
msg = MIMEText(‘你好,这是一份 python 发送的邮件。‘, ‘plain‘, ‘utf-8‘)
msg[‘Subject‘] = Header(subject, ‘utf-8‘)
msg[‘From‘] = sender 
msg[‘To‘] = recipient
smtpObj.sendmail(sender, recipient, msg.as_string())

smtpObj.quit()

相关推荐