随笔 - 49  文章 - 0  评论 - 6  阅读 - 10万

使用Python实现批量发送邮件

需求:

  给定收件人列表,使用指定的发件人给所有收件人逐个发送邮件,并可以指定邮件内容与附件。

Python代码:

复制代码
#!/usr/bin/env python3  
#coding: utf-8
import os
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email import encoders
  
#发送服务器配置
sender_host = 'smtp.163.com:25'
sender_user = 'xxx@163.com'
sender_pwd = 'xxx'
sender_name = 'xxx@163.com'
attach_file = '附件.pdf'

#加载邮件内容:第一行是邮件标题, 第二行是分割线, 第三行之后是邮件正文
default_title = ''
mail_content = ''
if not os.path.exists("邮件内容.txt"):
    print("文件 邮件内容.txt 不存在");
    exit(0);
contentFile = open("邮件内容.txt");
contentLines = contentFile.readlines();
contentFile.close();
if len(contentLines) < 3:
    print("文件 邮件内容.txt 至少三行");
    exit(0);
default_title = contentLines[0];
mail_content = ''.join(contentLines[2:]);

#加载收件人列表
if not os.path.exists("收件人列表.txt"):
    print("文件 收件人列表.txt 不存在");
    exit(0);
recvFile = open("收件人列表.txt");
recvLines = recvFile.readlines();
recvFile.close();

#添加附件
att = MIMEBase('application', 'octet-stream')  
att.set_payload(open(attach_file, 'rb').read())  
att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', attach_file));
encoders.encode_base64(att);

#发送邮件
smtp = smtplib.SMTP();
smtp.connect(sender_host);
smtp.login(sender_user, sender_pwd);
for recv in recvLines:
    msg = MIMEMultipart('alternative');
    msg['Subject'] = default_title;
    msg['From'] = sender_name;
    msg['To'] = recv;
    msg.attach(MIMEText(mail_content));
    msg.attach(att);
    smtp.sendmail(sender_name, recv, msg.as_string());
    print("已发送:" + recv);
smtp.quit();
复制代码

收件人列表示.txt:

10001@qq.com
10002@qq.com
10003@qq.com

邮件内容.txt

复制代码
测试标题
---------------------------------------------------------------------
XX你好,
    测试内容1
    测试内容2
    测试内容3

                                                 xxx
                                                 2015-11-13
复制代码

 

posted on   朱迎春  阅读(1268)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示