电子说
1、准备
先做一些准备,把邮件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 = '这里是邮件正文
'
2、发送邮件
连接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)
审核编辑:刘清
全部0条评论
快来发表一下你的评论吧 !