基本信息
源码名称:python实现自动发送邮件
源码大小:2.63KB
文件格式:.py
开发语言:Python
更新时间:2019-12-24
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍
实现自动发送邮件

# -*- coding: UTF-8 -*-

# 如何添加附件
import os,time
import smtplib
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
os.chdir(r'C:\Users\Administrator\Desktop\Automail')


def sendmail(subject, msg, toaddrs, fromaddr, smtpaddr, password):
    '''
    @subject:邮件主题
    @msg:邮件内容
    @toaddrs:收信人的邮箱地址
    @fromaddr:发信人的邮箱地址
    @smtpaddr:smtp服务地址,可以在邮箱看,比如163邮箱为smtp.163.com
    @password:发信人的邮箱密码
    '''

    mail_msg = MIMEMultipart()
    if not isinstance(subject, str):
        subject = str(subject, 'utf-8')
    mail_msg['Subject'] = subject
    mail_msg['From'] = fromaddr
    mail_msg['To'] = ','.join(toaddrs)
    # mail_msg.attach(MIMEText(msg, 'plain', 'utf-8')) #f发送文本文件
    mail_msg.attach(MIMEText(msg, 'html', 'utf-8'))  # 发送html格式邮件

    # 构造附件1
    att1 = MIMEText(open("Test.txt", 'rb').read(), 'base64', 'utf-8')  # 注意:直接读取中文文件名会报错
    att1["Content-Type"] = 'application/octet-stream'
    att1["Content-Disposition"] = 'attachment; filename="Test.txt"'
    mail_msg.attach(att1)

    # 构造附件2:添加中文附件名
    # att2 = MIMEText(open(u'测试文件2.docx', 'rb').read(), 'base64', 'utf-8')
    # att2["Content-Type"] = 'application/octet-stream'
    # att2["Content-Disposition"] = 'attachment; filename="test_file2.docx"'
    # mail_msg.attach(att2)

    try:
        s = smtplib.SMTP()
        s.connect(smtpaddr)  # 连接smtp服务器
        s.login(fromaddr, password)  # 登录邮箱
        s.sendmail(fromaddr, toaddrs, mail_msg.as_string())  # 发送邮件
        s.quit()
        print("邮件发送成功!")
    except Exception as e:
        print("Error: unable to send email")
        print(traceback.format_exc())


if __name__ == '__main__':
    fromaddr = 'XXXXXX@163.com'
    smtpaddr = 'smtp.163.com'
    toaddrs = ['XXXXXXXXX@qq.com','XXXXXXXX@163.com']
    subject = 'Hello,我是邮件主题'
    password = 'XXXXXXXXX'
    # msg = "Hello,我是邮件内容 !!!"
    msg = """
 <p>日报</P>
    <P>1.钉钉项目</P>
        <P>1.设备连接BT/WIFI/camera预览pass</P>
        <P>2.压力测试,重启500次</P>
        <P>3.修改脚本串口控制设备</P>
    <P>2.tmo项目<P>
    <P>1.版本待机功耗:3.23mA</P>
    <P>2.功耗测试case工具</p>
 <p><a href=http://www.baidu.com >测试邮件链接</a></p>
 """

    sendmail(subject, msg, toaddrs,fromaddr, smtpaddr, password)