Python发送邮件代码

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
import smtpli

def sendMail(to,cc,mailBody):
    # 服务器
    mail_host = 'smtp.office365.com'
    # 用户名
    mail_user = 'aaaaa@xxxx.com'
    # 密码
    mail_pass = '********'
    # 发送方邮箱
    sender = 'aaaaa@xxxx.com'
    # 邮件内容
    message = MIMEMultipart() #MIMEText(html_msg, 'html', 'utf-8')
    message.attach(MIMEText(mailBody, 'html', 'utf-8'))

    # 邮件主题
    message['Subject'] = '邮件主题'
    # 发送方信息
    message['From'] = sender
    # 接受方信息
    message['To'] = ','.join(to)
    # 抄送方信息
    message['Cc'] = ','.join(cc)  

    attach = r'D:\path'

    #读取文件夹下所有xlsx文件
    for f in listdir(attach):
        if f.endswith('.xlsx'):
            att1 = MIMEApplication(open(attach + f,'rb').read())
            att1["Content-Type"] = 'application/octet-stream'
            att1.add_header('Content-Disposition','attachment',filename=f)
            message.attach(att1)

    #读取照片
    fp1 = open(fl_path, 'rb')
    msgImage1 = MIMEImage(fp1.read())
    fp1.close()
    msgImage1.add_header('Content-ID', '<fl_path>')
    message.attach(msgImage1)

    fp2 = open(bc_path, 'rb')
    msgImage2 = MIMEImage(fp2.read())
    fp2.close()
    msgImage2.add_header('Content-ID', '<bc_path>')
    message.attach(msgImage2)

    # 登录并发送邮件
    try:
        smtpObj = smtplib.SMTP(mail_host)
        # 连接到服务器
        smtpObj.connect(mail_host, 587)
        # 登录到服务器
        smtpObj.ehlo()
        smtpObj.starttls()
        smtpObj.login(mail_user, mail_pass)
        # 发送
        smtpObj.sendmail(sender, to + cc, message.as_string())
        # 退出
        smtpObj.quit()
        print('send success')  
    except smtplib.SMTPException as e:
        print('send error', e)

if __name__ == '__main__':

    body = f"""<b><body>你好!</b><br>
    <b><body>你好:</b><br>

    #图片插入在这
    <b><p>< img src="cid:fl_path"></b><br>
    <b><body>内容:</b><br>
    <b><p>< img src="cid:bc_path"></b><br>

Leave a Comment