Python学习日志0720群发邮件 python 发送带附件的邮件,收到的附件名都变成了tcmime.1774.1903.2076.bin格式解决办法
该示例从excel表中读取客户名单,并群发邮件,判断性别修改称呼.添加附件,import openpyxl, timeimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.application import MIMEApplic
·
该示例从excel表中读取客户名单,并群发邮件,判断性别修改称呼.添加附件,
import openpyxl, time
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
usernames = {}
wb = openpyxl.load_workbook('邮件列表.xlsx')
ws = wb.active
for i in range(2, ws.max_row + 1):
usernames.setdefault(ws['A' + str(i)].value, {})
usernames[ws['A' + str(i)].value].setdefault('电子邮件', ws['D' + str(i)].value)
if str(ws['B' + str(i)].value) == '男':
usernames[ws['A' + str(i)].value].setdefault('称谓', '先生')
else:
usernames[ws['A' + str(i)].value].setdefault('称谓', '女士')
username = 'my@163.com'
passwrod = 'mypassword'
frommail = 'my@163.com'
subject = '*****公司的邀请函'
server = smtplib.SMTP(host='smtp.163.com', port=25)
server.login(user=username, password=passwrod)
def body(name, male):
texts = '''
尊敬的{}{}:
邀请您参加本公司于3月1日于****举办的公司展销会!'''.format(name, male)
return texts
for key in usernames.keys():
msg = MIMEMultipart()
msg['From'] = frommail
if usernames[key]['电子邮件'] is None or str(usernames[key]['电子邮件']).find('@') == -1:
print('{}没有填写电子邮件地址!或邮箱地址不正确!')
continue
print(key)
msg['To'] = usernames[key]['电子邮件']
msg['Subject'] = '***公司给' + key + '的邀请函'
msg.attach(MIMEText(body(key, usernames[key]['称谓'])))
with open('亲爱的.txt', mode='rb') as f:
attfile = f.read()
att = MIMEApplication(attfile) #最重要的两行.测试其他办法添加附件会导致tcmime.1774.1903.2076.bin的问题
att.add_header('Content-Disposition', 'attachment', filename="亲爱的.txt")
msg.attach(att)
try:
server.sendmail(frommail, usernames[key]['电子邮件'], msg.as_string()) #还有这行 测试过用server.send_message QQ邮箱接受的时候还是会把附件自动改成bin文件.
except smtplib.SMTPSenderRefused:
print('fail')
time.sleep(10)
except smtplib.SMTPDataError:
print('fail2')
time.sleep(10)
server.close()
新手日志,高手勿喷.
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)