python-简单的邮件发送

简单的邮件发送代码,干货如下:

# _*_ coding: utf-8 _*_

import smtplib
from email.mime.text import MIMEText

mailto_list = ["email@host"]
mail_host = "smtp.163.com"   # 这里以163为例
mail_user = "emailname"  # 只要name就好,不需要host
mail_pass = "password"  # 这里不是登陆密码而是授权码 在“设置”--“客户端授权码”中可设置
mail_postfix = "163.com"  # host


def send_mail(to_list, sub, content):
    me = "哈利骑着扫帚通知你" + "<" + mail_user + "@" + mail_postfix + ">"  # 这里设置的是收件人收到邮件里面的发件人名称和地址
    msg = MIMEText(content, _subtype="plain", _charset="utf-8")  # 这里设置邮件内容(不含附件)
    msg["Subject"] = sub  # 这里是邮件主题
    msg["From"] = me
    msg["To"] = ";".join(mailto_list)  # 可以批量发邮件

    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        server.login(mail_user, mail_pass)
        server.sendmail(me, to_list, msg.as_string())
        server.close()
        return True
    except Exception as exce:
        print("111", exce)
        return False

if __name__ == '__main__':
    if send_mail(mailto_list, "邮件主题", "邮件内容"):
        print("yes")
    else:
        print("no")

补充一点:
如果出现错误信息535, Error: authentication failed,说明授权码不对,要特别注意密码那里使用的是授权码不是密码,是授权码,授权码,授权码。

你可能感兴趣的:(python)