Python自动发送邮件代码

Python发送邮件成功的前提,应是先开启授权码。目前使用广泛的邮箱有:163邮箱、qq邮箱等。

163邮箱开启授权码的方法如下图:

qq邮箱开启授权码的方法如下图:

接下来代码的实现:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
class SendEmail:
    def email(self,body, attach):
        # 发送邮箱
        sender = '[email protected]'
        # 接收邮箱
        receivers = '[email protected]'

        msg = MIMEMultipart()
        #邮箱的主题
        msg['Subject'] = '测试报告'
        msg['From'] = sender
        msg['To'] = receivers

        content = MIMEText(body,'html','utf-8')
        msg.attach(content)
        #添加附件,并命名
        attachment = MIMEApplication(open(attach, 'rb').read())
        attachment.add_header('Content-Disposition', 'attachment', filename='report.rar')
        msg.attach(attachment)

        try:
            #连接邮箱的服务器及端口号,以163邮箱为例
            smtpObj = smtplib.SMTP_SSL('smtp.163.com','465')
            #登录邮箱:用户名及密码
            smtpObj.login(user='[email protected]', password='xxx')
            smtpObj.sendmail(sender, receivers, str(msg))
            smtpObj.quit()
            print("邮件发送成功")
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")


if __name__ == '__main__':
    #以同一目录中的report.html为例
    with open("./report.html",'r',encoding="utf-8") as file:
        body=file.read()
    #以同一目录中的report.rar为例添加附件
    SendEmail().email(body,"./report.rar")

猜你喜欢

转载自www.cnblogs.com/badbadboyyx/p/11937873.html
今日推荐