import smtplib
from email.mime.text import MIMEText
def email_test(**kwargs):
"""
测试邮件接口
:param kwargs:
:return:
"""
mail_host = kwargs.get("mail_host") # SMTP服务器
mail_port = int(kwargs.get("mail_port")) # SMTP端口
ssl = int(kwargs.get("ssl")) # 安全连接
sender_email = kwargs.get("sender_email") # 发件人EMail
certification = int(kwargs.get("certification")) # 认证
smtp_user = kwargs.get("smtp_user") # SMTP用户
mail_license = kwargs.get("mail_license") # 授权码/密码
mail_receivers = kwargs.get("mail_receivers") # 收件人
# TODO 邮件内容 --暂定
body_content = """这是一封测试邮件,%s,如果不是管理员,请忽略""" % mail_receivers
mm = MIMEMultipart('related')
# TODO 邮件主题 --暂定
subject_content = """邮件测试"""
# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱
mm["From"] = "<%s>" % sender_email # 发件人EMail
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱
mm["To"] = "<%s>" % mail_receivers
# 设置邮件主题
mm["Subject"] = Header(subject_content, 'utf-8')
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content, "plain", "utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)
try:
# 创建SMTP对象
if ssl: # 是否需要安全连接
stp = smtplib.SMTP_SSL(mail_host, mail_port)
else:
stp = smtplib.SMTP(mail_host, mail_port)
# stp = smtplib.SMTP_SSL(mail_host, timeout=3000)
# 设置发件人邮箱的域名和端口,端口地址为25
# set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
# stp.set_debuglevel(1)
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
if certification: # 是否需要认证
stp.login(smtp_user, mail_license)
# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
stp.sendmail(smtp_user, mail_receivers, mm.as_string())
print("-------Mail test successfully-------")
# 关闭SMTP对象
stp.quit()
except Exception as e:
print(e)
return True
python发送邮件
最新推荐文章于 2024-07-18 09:00:36 发布