群发邮件问题求助
我想把Excel工资表中工资明细发到表格中送指定的邮箱,遇到一个奇怪的问题,第一个邮件正常,自第二个起,主题和正文部分都会叠加前一个邮件内容。附代码如下,请大神指点。import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import openpyxl
import re
import time
# 设置登录及服务器信息
mail_host = 'smtp.163.com'
mail_user = '1xxxxxxxx@163.com'
mail_pass = 'T********FB'
message = MIMEMultipart()
message['From'] = '1xxxxxxx3@163.com'
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user, mail_pass)
ws = openpyxl.load_workbook('Salary.xlsx')['Sheet1']
result = list(ws.iter_rows(values_only=True))
title = result# 通过之前返回数据可以看出第一行是标题 我们直接索引获取第一行
datas = result# 剩下除了第一行就是用例数据了 直接截取
rules = r'+@+\.{2,}' #邮箱合规正则式
for row in datas:
dict1 = dict(zip(title, row))
name = dict1.get('姓名', '未发现"姓名"字段')
receivers = dict1.get('邮箱', '未发现"邮箱"字段')
if re.search(rules, receivers):
detail = ''
for k, v in dict1.items():
detail += str(k) + ":" + str(v) + '\n'
message['To'] = receivers
message['Subject'] = f'亲爱的{name},感谢您的努力付出!'
message.attach(MIMEText(detail, 'plain', 'utf-8'))
try:
# smtpObj = smtplib.SMTP()
# smtpObj.connect(mail_host, 25)
# smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail('1xxxxxxxx3@163.com', receivers, message.as_string())
print(f'{name}的邮件发送成功!')
time.sleep(2)
# smtpObj.quit()
except smtplib.SMTPException as err:
print(f'{name}的邮件发送失败,请检查相关设置!', err)
else:
print(f'{name}的邮箱地址{receivers}不合法,请检查更正!')
break 本帖最后由 歌者文明清理员 于 2023-6-18 23:23 编辑
你好!看到你的代码,问题可能出在对邮件正文和主题的处理上。在 for 循环中创建 message 对象之后,每次都直接修改了该对象的主题和正文部分。导致第二个邮件开始,每个邮件都包含了之前所有邮件的内容。正确的做法应该是每次都重新创建一个 MIMEMultipart 对象,例如:
for row in datas:
dict1 = dict(zip(title, row))
name = dict1.get('姓名', '未发现"姓名"字段')
receivers = dict1.get('邮箱', '未发现"邮箱"字段')
if re.search(rules, receivers):
detail = ''
for k, v in dict1.items():
detail += str(k) + ":" + str(v) + '\n'
message = MIMEMultipart()# 新建 MIMEMultipart 对象
message['To'] = receivers
message['Subject'] = f'亲爱的{name},感谢您的努力付出!'
message.attach(MIMEText(detail, 'plain', 'utf-8'))
try:
smtpObj.sendmail('1xxxxxxxx3@163.com', receivers, message.as_string())
print(f'{name}的邮件发送成功!')
time.sleep(2)
except smtplib.SMTPException as err:
print(f'{name}的邮件发送失败,请检查相关设置!', err)
else:
print(f'{name}的邮箱地址{receivers}不合法,请检查更正!')
break
这样就可以避免每封邮件内容重叠的问题。
页:
[1]