从列表发送电子邮件后,为什么字段TO为空?

时间:2013-09-15 19:16:52

标签: python email smtplib

我有以下代码从email.txt制作一个列表,然后向每个项目发送电子邮件。我使用列表而不是循环。

#!/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) ) 

当用户收到电子邮件时,他无法看到字段TO,因为此字段将为空。我希望收件人在电子邮件中看到TO字段一次。 我该怎么做?

1 个答案:

答案 0 :(得分:2)

to的邮件标题值设置为:

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

您可能必须从您从文件中读取的to列表中填充该值。因此,您可能必须一次一个地迭代所有值,或者将它们全部一起迭代,从而构建它的邮件提供程序如何支持它。

类似的东西:

#!/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()
  

无需嵌套try块。

     

您可以在循环外部创建连接,并保持打开状态,直到发送完所有邮件,然后将其关闭。

     

这不是复制粘贴代码,我也没有测试过。请用它来实施合适的解决方案。

相关问题