1

我有以下代码,它从 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 字段,因为该字段将为空。我希望收件人在电子邮件中看到一次收件人字段。我该怎么做?

4

1 回答 1

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块。

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

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

于 2013-09-15T19:19:39.043 回答