在现代工作环境中,我们经常需要向多个收件人发送个性化的邮件。通过使用Python编程语言,我们可以自动化这个过程,从Excel文件中读取收件人和相关数据,并发送定制的邮件。
首先,导入所需的库:
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os
from email.header import Header
sender\_email = 'your\[email protected]'
sender\_password = 'your\_password'
smtp\_server = 'smtp.example.com'
smtp\_port = 587
server = smtplib.SMTP(smtp\_server, smtp\_port)
server.starttls() # 开启TLS加密
server.login(sender\_email, sender\_password)
df = pd.read\_excel('path\_to\_excel\_file.xlsx')
employee\_names = df['员工姓名'].unique()
employee\_emails = {
'张三': '[email protected]',
'李四': '[email protected]',
'王五': '[email protected]',
# 添加更多员工和邮箱信息
}
for employee\_name in employee\_names:
employee\_data = df[df['员工姓名'] == employee\_name] # 创建员工的数据
# 生成员工的 Excel 文件
employee\_data\_filename = f'{employee\_name}.xlsx'
employee\_data.to\_excel(employee\_data\_filename, index=False)
# 创建邮件
msg = MIMEMultipart()
msg['From'] = sender\_email
msg['To'] = employee\_emails.get(employee\_name, '') # 根据员工姓名获取邮箱
msg['Subject'] = '拆分数据通知'
body = f"尊敬的{employee\_name},您的拆分数据已经准备好,请查收附件。"
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open(employee\_data\_filename, 'rb') as file:
part = MIMEApplication(file.read(), Name=os.path.basename(employee\_data\_filename))
part.add\_header('Content-Disposition', 'attachment', filename=Header(os.path.basename(employee\_data\_filename), 'utf-8').encode())
msg.attach(part)
# 发送邮件
server.sendmail(sender\_email, employee\_emails.get(employee\_name, ''), msg.as\_string())
# 删除生成的员工数据文件
os.remove(employee\_data\_filename)
# 退出SMTP连接
server.quit()
通过上述Python脚本,我们可以批量发送个性化的邮件。我们首先设置发件人邮箱和密码,然后指定SMTP服务器和端口号。接下来,我们读取包含员工信息的Excel文件,并获取唯一的员工姓名列表和对应的邮箱地址。然后,我们遍历员工数据,并为每个员工创建邮件,附带相应的附件。最后,我们通过SMTP服务器发送邮件,并在发送完成后删除生成的员工数据文件。
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os
from email.header import Header
# 设置发件人邮箱和密码
sender\_email = '[email protected]'
sender\_password = '授权码'
# 设置SMTP服务器和端口(QQ邮箱的SMTP服务器和端口)
smtp\_server = 'smtp.163.com'
smtp\_port = 25
# 创建SMTP连接
server = smtplib.SMTP(smtp\_server, smtp\_port)
server.starttls() # 开启TLS加密
# 登录邮箱
server.login(sender\_email, sender\_password)
# 读取原始 Excel 文件
df = pd.read\_excel('C:\\Users\\liuchunlin2\\Desktop\\测试数据\\员工.xlsx')
# 获取唯一的员工姓名列表
employee\_names = df['员工姓名'].unique()
# 获取员工姓名和对应的邮箱地址,假设这些信息存储在一个字典中
employee\_emails = {
'刘备': '[email protected]',
'孙权': '[email protected]',
'曹操': '[email protected]',
# 添加更多员工和邮箱信息
}
# 遍历员工数据并发送邮件
for employee\_name in employee\_names:
# 创建员工的数据
employee\_data = df[df['员工姓名'] == employee\_name]
# 生成员工的 Excel 文件
employee\_data\_filename = f'{employee\_name}.xl