这是一个使用腾讯企业邮箱发送邮件的Python脚本,支持发送给多人。使用方式极其简洁。示例用法详见代码底部。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import logging
import time
class QQMailMan():
def __init__(self, user, password):
# 发件人邮箱账号
self.user = user
# user登录邮箱的用户名,password登录邮箱的密码(授权码,即客户端密码,非网页版登录密码),但用腾讯邮箱的登录密码也能登录成功
self.password = password
def connect(self):
try:
self.smtp_host = "smtp.exmail.qq.com"
self.smtp_port = 465
self.mailman = smtplib.SMTP_SSL(self.smtp_host, self.smtp_port)
self.mailman.set_debuglevel(1)
self.mailman.login(self.user, self.password)
except Exception:
raise(Exception)
def close(self):
self.mailman.quit()
def mail_to(self, to_addrs, subject, content):
"""
发送邮件到指定地址(也可以是地址列表或用,拼接的字符串)
"""
msg = MIMEText(content, 'plain', 'utf-8')
if type(to_addrs) == str:
msg['To'] = to_addrs
to_addrs = to_addrs.split(',')
elif type(to_addrs) == list:
msg['To'] = ','.join(to_addrs)
else:
logging.error("邮件地址类型错误,必须为str(可以用,拼接)或list")
return
time.sleep(1)
msg['From'] = formataddr(["自动发送的邮件", self.user])
# 邮件的主题
msg['Subject'] = subject
try:
ret = self.mailman.sendmail(self.user, to_addrs, msg.as_string())
logging.info("成功发送邮件至:{} {}".format(to_addrs, ret))
except Exception:
logging.error("发送邮件失败: {} {} {}".format(to_addrs, ret, Exception))
if __name__ == "__main__":
content_template = """
您好!
您的账号信息如下:
用户名:{}
密码:{}
----------------------------------------------------------------
本邮件为自动发出,无需回复,谢谢!
"""
user = '您的邮箱地址'
password = '邮箱密码或授权码'
qqmail = QQMailMan(user, password)
qqmail.connect()
to_addrs = ['收件人地址1', '收件人地址2(非必须)']
content = content_template.format("username", "password")
qqmail.mail_to(to_addrs, "您的账号信息", content)
qqmail.close()