我的邮件发送程序在Python中的错误

时间:2014-02-03 15:34:31

标签: python email smtp

我正在尝试使用smtp服务器和Python创建邮件发送脚本。 我使用csv来存储地址,然后脚本使用它们来创建使用电子邮件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]发送的。

输出:

from: asv@acdc.co.il
[+] emali send from asv@acdc.co.il to orhalimi@mailinator.com
from: asv@acdc.co.il
[+] emali send from sss@Nisha.com to  or@mailinator.com
即使msg[from]发生了更改,

f也不会在下一轮循环中发生变化。但是msg['To']没有问题。

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

编辑:显示如何定义msg

我创建了一个多部分消息,附加了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))

编辑2:尝试建议后的内容

你对同样的行为是正确的。当我添加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中重新定义。

1 个答案:

答案 0 :(得分:3)

因为它附加了而不是替换你的msg属性值。

您可以使用replace_headerdel

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

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

其他方法是清除属性,并指定值 -

del msg['From']
msg['From'] = f