python -- 发送邮件

介绍:

发邮件需要用到python两个模块,smtplib和email,这俩模块是python自带的,只需import即可使用。smtplib模块主要负责发送邮件,email模块主要负责构造邮件。其中MIMEText()定义邮件正文,Header()定义邮件标题。MIMEMulipart模块构造带附件。

大致流程:

1、发件人需要登录邮箱、涉及发件人的登录账号和密码----smtplib

2、构造邮件内容:1)确定邮件内容,涉及附件的话,需要设置有邮件体对象----MIMEMulipart

                   msg_root = MIMEMultipart('mixed')

                                  2)邮件内容:发件人、收件人、主题、正文、附件

                             其中:收件人包括单人收件  和  多人收件

                                    主题需要导入:from email.header import Header

                                   编辑正文需要导入:from email.mime.text import MIMEText

3、使用smtplib发送邮件

4、各模块语法介绍:https://www.cnblogs.com/zhangxinqi/p/9113859.html

导图总结如下:

python -- 发送邮件_第1张图片

 python -- 发送邮件_第2张图片

python -- 发送邮件_第3张图片

 

python -- 发送邮件_第4张图片

本人代码样例:

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

import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from utils.logger import Logger

logger = Logger(logger='SendEmail').get_log()

class SendEmail():

    def send_email(self,to,filename):
        #设置账户和密码
        sender_email = '[email protected]'
        sender_pass = '####'
        logger.info('设置发件邮箱登录账号和密码')
        #设置总的邮件体对象,对象类型为mixed
        msg_root = MIMEMultipart('mixed')
        logger.info('设置总的邮件体对象,对象类型为mixed')
        #邮件添加的头尾信息等
        msg_root['From'] = 'amy@mailcom'
        logger.info('设置发件人的邮箱信息')
        msg_root['To'] = to
        logger.info('设置收件人的邮箱信息')
        #邮件主题,显示在接收邮件的预览页面
        subject = 'python sendmail test successful'
        msg_root['subject'] = Header(subject,'utf-8')
        #构造文本内容
        text_info = 'happy everyday!!'
        text_sub = MIMEText(text_info,'plain','utf-8')
        msg_root.attach(text_sub)
        #构造附件
        html_file = open(filename,'rb').read()
        html = MIMEText(html_file,'base64','utf-8')
        #邮件内容
        html["Content-Type"] = 'application/octet-stream'
        html['Content-Disposition'] = 'attachment;filename="jetty_report.html"'
        msg_root.attach(html)

        #发送邮件
        try:
            sftp_obj = smtplib.SMTP('lsmtp.com',25)
            sftp_obj.login(sender_email,sender_pass)
            sftp_obj.sendmail(sender_email,to,msg_root.as_string())
            sftp_obj.quit()
            print('sendemail successful')
        except Exception as e:
            print('sendemail failed next is the reason')
            print(e)


if __name__ == '__main__':
    # to = '[email protected]'
    to = ['[email protected]','[email protected]','[email protected]']
    to = ';'.join(to)
    logger.info('收件人为多个')
    file_name = r'D:\api\test_report\jetty_report.html'
    send = SendEmail()
    send.send_email(to,file_name)

参考:

https://www.cnblogs.com/du-hong/p/10812533.html

https://www.cnblogs.com/du-hong/p/10819199.html

https://www.cnblogs.com/du-hong/p/10819319.html

你可能感兴趣的:(Python学习笔记)