使用python发送邮件带不同种类的附件

注意:一定要先获取授权码,授权码的获取可以自己百度(qq邮箱的授权码获取)

import datetime
import smtplib
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"      # SMTP服务器
mail_user = "1020487224"       	       # 用户名
mail_pass = "sdgfdsagdasg"               # 授权密码,非登录密码

sender = '[email protected]'    # 发件人邮箱(最好写全, 不然会失败)
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

content = '我用Python'
title = '人生苦短'  # 邮件主题


file_name_new1=r"E:\123\文档\测试开发\django\05.html"
file_name_new2="run_script.py"
file_name_new3="p123.jpg"

def sendEmail():

    message = MIMEText(content, 'plain', 'utf-8')  # 内容, 格式, 编码
    # message = MIMEText(content, "html")
    message['From'] = "{}".format(sender)
    message['To'] = ",".join(receivers)
    message['Subject'] = title
    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
        smtpObj.login(mail_user, mail_pass)  # 登录验证
        smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
        print("mail has been send successfully.")
    except smtplib.SMTPException as e:
        print(e)

def sendEmail2():

    message = MIMEMultipart()  # 内容, 格式, 编码
    message['From'] = "{}".format(sender)
    message['To'] = ",".join(receivers)
    message['Subject'] = title

    #添加邮件内容
    text_content = MIMEText(content)
    #text_content = MIMEText(content, "html")
    message.attach(text_content)
    # 添加附件(html,py,txt等文件)
    annex1 = MIMEApplication(open(file_name_new1, 'rb').read())  # 打开附件
    annex1.add_header('Content-Disposition', 'attachment', filename=file_name_new1)
    message.attach(annex1)

    annex2 = MIMEApplication(open(file_name_new2, 'rb').read())  # 打开附件
    annex2.add_header('Content-Disposition', 'attachment', filename=file_name_new2)
    message.attach(annex2)

    # 添加图片
    # 1.
    annex3 = MIMEApplication(open(file_name_new3, 'rb').read())  # 打开附件
    annex3.add_header('Content-Disposition', 'attachment', filename=file_name_new3)
    message.attach(annex3)
    #2.
    annex4 = MIMEImage(open(file_name_new3, 'rb').read())  # 打开附件
    annex4.add_header('Content-Disposition', 'attachment', filename=file_name_new3)
    message.attach(annex4)

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
        smtpObj.login(mail_user, mail_pass)  # 登录验证
        smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
        smtpObj.quit()
        print("mail has been send successfully.")
    except smtplib.SMTPException as e:
        print(e)

if __name__ == '__main__':
    sendEmail2()

猜你喜欢

转载自blog.csdn.net/qq_43534980/article/details/112974823