[Python3]SMTP发送邮件(一)

# python3
import smtplib
from email.mime.text import  MIMEText
from email.header import Header

# 发送者
sender = 'zhengxiaodong@trusfort.com'  
# 发送者 密码
password = '*****'  
# 接收邮件方
receivers = ['sheldon74@qq.com', '921804412@qq.com']  

# 邮件 发送内容
# 邮件正文内容——文本方式 :第三个参数:第一个为文本内容,第二个 plain 设置文本格式 , 第三个 utf-8 设置编码方式
message = MIMEText('Python 邮件发送测试……','plain','utf-8')

# 发送者
message['From'] = Header(sender, 'utf-8')  
# 接收者
message['To'] = Header("sheldon74@qq.com","utf-8")    # 单人接收
message['To'] = Header(",".join(receivers),'utf-8')    # 多人接收,首先需要将list集合转换成字符串(或其他能设置编码方式的数据类型)
# 邮件 标题
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject,'utf-8')    # 标题

try:
    # 构建 SMTP 对象 并连接     参数:服务器地址及端口
    smtpObj = smtplib.SMTP('smtp.trusfort.com',25)
    # smtpObj = smtplib.SMTP()
    # smtp.connect('smtp.trusfort.com',25) # 服务器地址及端口
    
    # 登陆,必须,否则发送不成功
    smtpObj.login(sender,password)
    # 发送邮件 参数:发送者,接收者,text 正文内容
    smtpObj.sendmail(sender,receivers,message.as_string())
    print("Success:邮件发送成功")
except smtplib.SMTPException:
    print("Error:无法发送邮件")

 

posted @ 2018-08-04 16:48  CryDongle  阅读(24)  评论(0编辑  收藏  举报