使用Python同时向多个抄送和多个收件人发送电子邮件

3

我尝试分别只使用多个to和多个cc,这样可以正常工作,但当我同时使用两者时,会出现以下错误:

文件

"path\Continuum\anaconda2\envs\mypython\lib\smtplib.py", line 870, in sendmail senderrs[each] = (code, resp) TypeError: unhashable type: 'list'"

代码:

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()

1
请发布调用代码。 - Ken Y-N
如果你不能在“text/plain”部分放置任何有用的内容,也许你根本不应该生成“multipart/alternative”。(我知道有些人这样做是为了向某些垃圾邮件过滤器发出空的信号,但是发送垃圾邮件对收件人造成了不便。) - tripleee
2个回答

7

附加的 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())

1
@GufranHasan,您能告诉我为什么要给我投反对票吗?这样我就可以改进我的回答了。 - hamini ts
1
我没有给你的帖子点踩,只是为了吸引用户编辑了一下它。 - Gufran Hasan

4

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())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接