美文网首页
python简单实现邮件发送

python简单实现邮件发送

作者: KS保 | 来源:发表于2021-08-16 11:25 被阅读0次

注:阿里云实例服务器默认禁止了25端口,可通过465端口加密发送邮件

# -*- coding: utf-8 -*-
import smtplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

mail_info = {
    "host": "smtp.xxx.com:465",
    "sender": "xxx",
    "license": "xxx",
    "receivers": ["xxx.com", "xxx.com"]
}

def send_mail(subject, body):
    """
    发送邮件
    :subject : 邮件主题
    :body : 邮件正文内容
    """
    host = mail_info.get("host")
    sender = mail_info.get("sender")
    mail_license = mail_info.get("license")
    receivers = mail_info.get("receivers")

    mm = MIMEMultipart('related')

    mm["From"] = "invita<" + sender + ">"
    mm["To"] = ";".join(receivers)
    # 设置邮件主题
    mm["Subject"] = Header(subject,'utf-8')

    # 构造文本:正文内容,文本格式,编码方式
    message_text = MIMEText(body,"plain","utf-8")
    # 向MIMEMultipart对象中添加文本对象
    mm.attach(message_text)

    try:
        # 创建SMTP对象
        stp = smtplib.SMTP_SSL(host)
        stp.login(sender, mail_license)
        stp.sendmail(sender, receivers, mm.as_string())
        print("邮件发送成功")
    except:
        print("邮件发送失败")
    stp.quit()


if __name__ == "__main__":
    """发送邮件"""
    send_mail("测试", "content")

相关文章

网友评论

      本文标题:python简单实现邮件发送

      本文链接:https://www.haomeiwen.com/subject/sesmbltx.html