Or Halimi Or Halimi - 2 months ago 6
Python Question

Bug in my mail sending program in Python

I am trying to create a mail sending script using smtp server and Python.
I am using csv to store the addresses, and then the script use them to create sending request using 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()


here is the problematic part. It seems that all the emails are sent only from the first
msg[from]
that I define.

output:

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]
doesn't get change in the next round of the loop even if
f
changed. but
msg['To']
work without problem.

Really weird,
Thanks for any help.

Edit: Show how msg is defined

I make a multipart message that attach html with option to attach file.

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: After trying the suggesting stuff

You are right about the same behavior. when I added
print('To: '+str(msg['From']))
The output got stuck on the first value.
output:

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


but when I change it to replace and set them before its work.
output:

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


Anyone know why? I remember list can redefine easy in python.

Answer

Its because its appending and not replacing your msg attribute value.

You can use replace_header or del .

If you use replace make sure the check of attribute exists or not.

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

Other way is clearing the attribute, and assign value -

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