首页 > 代码库 > python3使用stmplib发送邮件

python3使用stmplib发送邮件

 

代码如下:

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr

# 第三方 SMTP 服务
mail_host = "smtp.exmail.qq.com"
mail_port = 465  # 也可能是25,看情况。SMTPS的话一般是465
mail_user = "a@a.com"
mail_pass = "aaa"   # 密码或邮箱授权码

mail_sender = a@a.com
mail_receivers = [a@a.com]

subject = 邮件主题
message = MIMEText(邮件内容, plain, utf-8)  # plain表示邮件类型
message[From] = formataddr(["发件人别称", "a@a.com"])
message[To] = formataddr(["收件人别称", "a@a.com"])
message[Subject] = Header(subject, utf-8)


def sendmail(host, port, sender, password, recvivers, meassage):
    try:
        mail_obj = smtplib.SMTP_SSL()  # 邮件服务器使用 SMTPS 的时候用 SMTP_SSL
        mail_obj.connect(host, port)
        mail_obj.login(sender, password)
        mail_obj.sendmail(sender, recvivers, meassage.as_string())
        mail_obj.quit()
        print("Send sucessful")
        return True
    except Exception as e:
        err = "Send Failed for reason:\n {}".format(e)
        print(err)
        return False


sendmail(mail_host, mail_port, mail_sender, mail_pass, mail_receivers, message)

 

python3使用stmplib发送邮件