質問

I have the following code which makes a list from email.txt and then sends emails to each item. I use a list instead of a loop.

#!/usr/bin/python
# -*- coding= utf-8 -*-

SMTPserver = '' 

import sys
import os
import re

import email
from smtplib import SMTP      
from email.MIMEText import MIMEText

body="""\
hello
"""

with open("email.txt") as myfile:
    lines = myfile.readlines(500)
    to  = [line.strip() for line in lines] 

try:
    msg = MIMEText(body.encode('utf-8'), 'html', 'UTF-8')
    msg['Subject']=  'subject' 
    msg['From']   = email.utils.formataddr(('expert', 'mymail@site.com'))
    msg['Content-Type'] = "text/html; charset=utf-8"

    conn = SMTP(SMTPserver)
    conn.set_debuglevel(False)
    conn.login('info', 'password')
    try:
        conn.sendmail(msg.get('From'), to, msg.as_string())
    finally:
        conn.close()

except Exception, exc:
    sys.exit( "mail failed; %s" % str(exc) ) 

When the user receives the email he can't see the field TO because this field will be empty. I would like the recipient to see the TO field once in the email. How should I do this?

役に立ちましたか?

解決

Set message header value for to also as:

msg['to'] = "someone@somesite.com"

You may have to populate that value from the to list that you've read from the file. So you may have to iterate over all the values either one at a time or all of them together, structuring it how your mail provider supports it.

Something like:

#!/usr/bin/python
# -*- coding= utf-8 -*-

SMTPserver = '' 

import sys
import os
import re
import email
from smtplib import SMTP      
from email.MIMEText import MIMEText

body="""\

hello

"""

with open("email.txt") as myfile:
    lines = myfile.readlines(500)
    to  = [line.strip() for line in lines] 

for to_email in to:    
    try:
        msg = MIMEText(body.encode('utf-8'), 'html', 'UTF-8')
        msg['Subject'] = 'subject' 
        msg['From'] = email.utils.formataddr(('expert', 'mymail@site.com'))
        msg['Content-Type'] = "text/html; charset=utf-8"
        msg['to'] = to_email

        conn = SMTP(SMTPserver)
        conn.set_debuglevel(False)
        conn.login('info', 'password')
        conn.sendmail(msg.get('From'), to, msg.as_string())

    except Exception, exc:
        sys.exit( "mail failed; %s" % str(exc))
    finally:
        conn.close()

There is no need to have nested try blocks.

You may create the connection outside the loop and keep it open until all the mails are sent and close it afterwards.

This is not a copy-paste code, I haven't tested it too. Please use it to implement a suitable solution.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top