使用 python 同时向多个 CC 和多个 TO 收件人发送电子邮件



分别尝试使用多个to和多个cc,这工作正常,但是当我同时尝试两者时,我收到错误:

文件

"path\Continuum\anaconda2\envs\mypython\lib\smtplib.py", 第 870 行,在 sendmail senderrs[each] = (code, resp( 类型错误: 不可散列类型:"列表">

法典:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
strFrom = 'fasdf@dfs.com'
cc='abc.xyz@dfa.com, sdf.xciv@lfk.com'
to='sadf@sdfa.com,123.lfadf@fa.com'
msg = MIMEMultipart('related')
msg['Subject'] = 'Subject'
msg['From'] = strFrom
msg['To'] =to
msg['Cc']=cc
#msg['Bcc']= strBcc
msg.preamble = 'This is a multi-part message in MIME format.'

msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)

msgText = MIMEText('''<html>
<body><p>Hello<p>
        </body>
        </html> '''.format(**locals()), 'html')
msgAlternative.attach(msgText)

import smtplib
smtp = smtplib.SMTP()
smtp.connect('smtp address')
smtp.ehlo()
smtp.sendmail(strFrom, to, msg.as_string())
smtp.quit()

附加Tofrom应该是一个字符串,sendmail 应该始终采用列表的形式。

cc=['abc.xyz@dfa.com', 'sdf.xciv@lfk.com']
to=['sadf@sdfa.com','123.lfadf@fa.com']
msg['To'] =','.join(to)
msg['Cc']=','.join(cc)   
toAddress = to + cc    
smtp.sendmail(strFrom, toAddress, msg.as_string())

to 参数应该是要将邮件发送到的所有地址的列表。 To:Cc:的划分基本上仅用于显示目的;SMTP只有一个收件人序列,每个地址转换为一个RCPT TO命令。

def addresses(addrstring):
    """Split in comma, strip surrounding whitespace."""
    return [x.strip() for x in addrstring.split(',')]
smtp.sendmail(strFrom, addresses(to) + addresses(cc), msg.as_string())

相关内容

最新更新