Python3群发邮件(支持附件)

1. 实现功能

  • 支持群发给多个人
  • 支持带附件发送

2. 核心代码

def send_email(smtp_server, sender_name, from_mail, mail_pass, to_mails, subj, body, attachment=None):
    msg = MIMEMultipart()
    msg['From'] = Header(sender_name, 'utf-8')
    msg['To'] = to_mails
    msg['Subject'] = Header(subj, 'utf-8')
    msg.attach(MIMEText(body, 'plain''utf-8'))

    if attachment and os.path.exists(attachment):
        with open(attachment, 'rb'as f:
            mime = MIMEApplication(f.read())
            mime.add_header('Content-Disposition''attachment', filename=attachment)
            msg.attach(mime)
    try:
        s = smtplib.SMTP()
        s.connect(smtp_server, 25)
        s.login(from_mail, mail_pass)
        s.sendmail(from_mail, to_mails.split(','), msg.as_string())
        s.quit()
        print('发送成功')
    except Exception as e:
        print(f'Error: {e}')

3. 完整代码

https://gitee.com/ferrisyu/CodingSea/tree/master/Python/email

4. 使用方法

# 使用说明:
python3 email_send.py smtp服务 发件人名字 发件人邮箱 发件箱密码 收件箱 邮件标题 邮件内容 附件文件路径

# 例如:
python3 email_send.py smtp.163.com 编程之海 codingsea@163.com QOFXWSDVHLMDRGFT 2481498999@qq.com,342345@qq.com 标题测试 body测试 attachFile.txt
  • 注意“发件箱密码”,不是邮箱的登录密码。

    现在的邮箱基本都要到到后台设置中生成授权码,再使用这个授权码作为密码使用。

    例如163邮箱,要在这里配置:

  • 多个发件人邮箱,使用逗号隔开,例如:2481498999@qq.com,342345@qq.com

  • “附件文件路径”可选,不填就不发送附件。

建站  ·  开发  ·  读书  ·  教程
↑长按或扫码关注“编程之海”公众号↑
↑长按或扫码关注“编程之海”公众号↑
编程之海 版权所有丨如未注明,均为原创丨转载请注明转自:https://codingsea.com/python_send_email/
0 0 投票数
文章评分
订阅评论
提醒
guest
0 评论
内联反馈
查看所有评论

0

0

247

0
希望看到您的想法,请您发表评论x