ExASIC
分享让工作更轻松

用python发邮件(SMTP SSL协议)

准备

先做一些准备,把邮件SMTP服务器、收发mail、邮件标题和正文准备好。

mailhost = 'smtp.server.com'
mailport = 465
mailuser = 'mymail@server.com'
mailpass = '123456'

mailfrom = 'mymail@server.com'
mailto = []
mailto.append('customer@server.com')
mailsubject = '这是测试邮件标题'
mailbody = '<p>这里是邮件正文</p>'

发送邮件

连接SMTP服务器,一般服务器要求用SSL,所以SMTP_SSL()来连接。再用login(user, password)来验证用户名和密码。登录成功后,就可以sendmail()来发邮件了。下面是示例代码:

import smtplib
from email.mime.text import MIMEText

msg = MIMEText(mailbody, 'html')
msg['From'] = mailfrom
msg['Subject'] = mailsubject
msg['To'] = ','.join(mailto)

try:
    mailserver = smtplib.SMTP_SSL(host=mailhost, port=mailport)
    #mailserver.set_debuglevel(1)
    mailserver.ehlo()
    mailserver.login(mailuser, mailpass)

    mailserver.sendmail(mailfrom, mailto, msg.as_string())
    mailserver.quit()
except Exception as e:
    print(e)
阅读数:
更多文章:文章目录
解惑专区
(支持markdown插入源代码)
欢迎使用ExASIC订阅服务
仅用于ExASIC最新文章通知,方便及时阅读。
友情链接: IC技术圈问答ReCclayCrazyFPGA