使用python smtplib 模块发送邮件
程序员文章站
2022-07-10 16:18:15
...
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
class Mail():
def __init__(self, receiver_emails, sender_email="*******@163.com", sender_passwd="******"):
self.sender_mail = sender_email # 发件人邮箱账号
self.sender_passwd = sender_passwd # 邮箱授权密码
self.receiver_emails = receiver_emails # 收件人邮箱
def send_mail(self, email_title, html_msg):
ret = True
try:
msg = MIMEText(html_msg, 'html', 'utf-8') # html格式的内容
msg['From'] = formataddr(["franklin", self.sender_mail]) # 发件人邮箱昵称、发件人邮箱账号
msg['To'] = ",".join(self.receiver_emails) # 收件人邮箱账号
msg['Subject'] = email_title # 邮件的主题
server = smtplib.SMTP("smtp.163.com", 25) # 发件人邮箱中的SMTP服务器,端口是25
server.login(self.sender_mail, self.sender_passwd)
server.sendmail(self.sender_mail, self.receiver_emails, msg.as_string()) #发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit()
except Exception as e:
print(e)
ret = False
return ret
if __name__ == '__main__':
to_users = ['1**********@qq.com', '*********@qq.com'] # 收件人邮箱账号
mail_title = "思南新闻6666"
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.runoob.com">这是一个链接</a></p>
"""
obj = Mail(to_users)
ret = obj.send_mail(mail_title, mail_msg)
if ret:
print("ok") # 发送成功则会返回ok
else:
print("failed") # 如果发送失败则会返回failed
运行结果
上一篇: 可乐就没气了真搞笑
推荐阅读