Python邮件发送程序中的Bug

2024-09-20 22:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用smtp服务器和Python创建一个邮件发送脚本。 我使用csv来存储地址,然后脚本使用它们来创建使用email lib的发送请求。在

for f, t in zip(FROM,TO):
    s = smtplib.SMTP('localhost')
    msg['From']= f
    msg['To'] = t  
    s.sendmail(f, t, msg.as_string())
    sleep(5)
    print('from: '+str(msg['From']))  #for debuging
    print('[+] emali send from {} to {}'.format(f,t)) 
    s.quit()

这是有问题的部分。似乎所有的电子邮件都是从我定义的第一个msg[from]发送的。在

输出:

^{pr2}$

即使msg[from]已更改,msg[from]也不会在下一轮循环中获得更改。但是msg['To']工作没有问题。在

真的很奇怪, 谢谢你的帮助。在

编辑:显示如何定义消息

我做了一个多部分的消息,用附加文件的选项附加html。在

msg = MIMEMultipart()
if not opts.subject: msg['Subject'] = ' '
else: msg['Subject'] = opts.subject
try:
    with open(opts.html,'r') as f:
        html = f.read()
    part1 = MIMEText(html, 'html')
    msg.attach(part1)
except Exception as e:
    print('html: '+ str(e))

if(opts.file):
    try:
        with open(opts.file, 'rb') as f:
            maintype, subtype = 'application', 'octet-stream'
            part2 = MIMEBase(maintype, subtype)
            part2.set_payload(f.read())
        encoders.encode_base64(part2)
        part2.add_header('Content-Disposition', 'attachment', filename=opts.file)
        msg.attach(part2)

    except Exception as e:
        print('file: '+ str(e))

Edit2:在尝试了建议之后

你的行为是一样的。当我添加print('To: '+str(msg['From']))时,输出被卡在第一个值上。 输出:

from: asv@acdc.co.il
To: asv@acdc.co.il
[+] emali send from asv@acdc.co.il to orhalimi@mailinator.com
from: asv@acdc.co.il
To: asv@acdc.co.il
[+] emali send from sss@Nisha.com to  or@mailinator.com

但当我把它换掉,把它们放在工作之前。 输出:

from: asv@acdc.co.il
To: orhalimi@mailinator.com
[+] emali send from asv@acdc.co.il to orhalimi@mailinator.com
from: sss@Nisha.com
To:  or@mailinator.com
[+] emali send from sss@Nisha.com to  or@mailinator.com

有人知道为什么吗?我记得list可以在python中重新定义easy。在


Tags: tofromcomsendhtmlasmsgil
1条回答
网友
1楼 · 发布于 2024-09-20 22:21:32

这是因为它附加而不是替换msg属性值。在

您可以使用replace_headerdel。在

如果使用replace,请确保属性的检查是否存在。在

if msg.has_key('From'):
    msg.replace_header('From', f)
else:
    msg['From'] = f

另一种方法是清除属性并赋值-

^{pr2}$

相关问题 更多 >

    热门问题