python发送邮件的几种常用方法

第一种是最常见的,smtp发送

import smtplib
import sys
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os


def sendEmail(mail_sender, to_list, sub, content, attach_list = [], _subtype="html"):
    """
    使用smtp发送邮件
    :param mail_sender: 发件人
    :param to_list: 收件人列表,用,间隔
    :param sub: 主题
    :param content: 内容
    :param attach_list:附件
    :param _subtype: 读取内容用的方式,不传html的话改成plain
    :return:
    """
    msg = MIMEMultipart()
    msg['subject'] = sub
    msg['From'] = mail_sender
    msg['To'] = to_list
    try:
        msg.attach(MIMEText(content, _subtype,'utf-8')) #用html的方法是更方便于word文档作为内容发送,可以先讲word转换成html,然后写入其中
        s = smtplib.SMTP('123.com', 25)
        # s.login()
        s.starttls()
        if attach_list:
            for att_path in attach_list:
                path_arr = att_path.split(os.path.sep)
                file_name = path_arr[len(path_arr) - 1]
                att1 = MIMEText(open(att_path,'rb').read(), 'base64','utf-8')
                att1.add_header('Content-Disposition', 'attachment', filename=file_name) #用这个方法可以避免附件乱码
                msg.attach(att1)
        s.sendmail(mail_sender, to_list.split(u','), msg.as_string())
        s.close()
        print("999921||业务数据处理||邮件发送成功")
        return True
    except Exception as e:
        sys.stderr.write("999931||{}".format(traceback.format_exc(limit=None, chain=True)))
        sys.stderr.write("0001")
        return False

第二种是用outlook发送的,这个大家借鉴使用

import os
from time import sleep
import autoit as au
import win32com.client

class OutlookUtills:
    def __init__(self):

        outlook = win32com.client.Dispatch("outlook.Application ")# outlook.Visible = True
        self.mail = outlook.CreateItem(0)
        self.mail.Display()

    def sendEmail(self, addressee, subiect, AttachmentsPath=[], body=None):
        """
        若body为默认值None则自动粘贴剪切板中内容进行发送
        :param addressee: 收件人
        :param subiect: 主题
        :param AttachmentsPath: 附件名称
        :param body: 正文
        :return:
        """
        self.mail. To = addressee
        self.mail.subject = subiect
        if AttachmentsPath == []:
            print("该邮件无附件")
        else:
            for Attachments in AttachmentsPath:
                self.mail.Attachments.Add(Attachments)
                print("地址:{},附件添加成功!!")
        sleep(2)
        if body == None:
            self.mail.body = ""
            au.send('^v')
            print("正文已从剪切板拷贝")
        else:
            self.mail.body = body
            print("正文由函数进行输入")
        sleep(1)
        self.mail.Send()

if __name__ == '__main__':
    my_outlook = OutlookUtills()


第三种是正文需要用到表格的,我在这里给大家一个示例,具体表格怎么改自行发挥

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


class Mail:
    def __init__(self):
        # 第三方 SMTP 服务

        self.mail_host = "smtp.qq.com"  # 填写邮箱服务器:这个是qq邮箱服务器,直接使用smtp.qq.com
        self.mail_pass = "ahlwsnkajalubeif"  # 填写在qq邮箱设置中获取的授权码
        self.sender = '[email protected]'  # 填写邮箱地址
        self.receivers = ['[email protected]']  # 填写收件人的邮箱,QQ邮箱或者其他邮箱,可多个,中间用,隔开

    def send(self):

        self.mail_host = "smtp.qq.com"  # 填写邮箱服务器:这个是qq邮箱服务器,直接使用smtp.qq.com
        self.mail_pass = "ahlwsnkajalubeif"  # 填写在qq邮箱设置中获取的授权码
        self.sender = '[email protected]'  # 填写邮箱地址
        self.receivers = ['[email protected]']  # 填写收件人的邮箱,QQ邮箱或者其他邮箱,可多个,中间用,隔开
        insert = "152371200010240002潘金莲tar152371200010240002.tar20220426-1545否152371200010240002潘金莲tar152371200010240002.tar20220426-1545否"

        head = \
            """
            
                
                
            
            """
        body = \
            """
            
            

表格中的数据为当天云开户信息下载及CRM上传情况


掌厅不存在身份证不一致情况

身份证号姓名文件类型文件名上传时间是否上传成功

""".format(insert) html_msg = "" + head + body + "" html_msg = html_msg.replace('\n', '').encode("utf-8") message = MIMEText(html_msg, 'html', 'utf-8') message['From'] = Header("小胖子xpp", 'utf-8') #邮件发送者姓名 message['To'] = Header("小胖子xpp", 'utf-8') #邮件接收者姓名 subject = '测试' #发送的主题 message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP_SSL(self.mail_host, 465) #建立smtp连接,qq邮箱必须用ssl边接,因此边接465端口 smtpObj.login(self.sender, self.mail_pass) #登陆 smtpObj.sendmail(self.sender, self.receivers, message.as_string()) #发送 smtpObj.quit() print('发送成功!!') except smtplib.SMTPException as e: print('发送失败!!') if __name__ == '__main__': mail = Mail() mail.send()

你可能感兴趣的:(python,开发语言)