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

2022-05-27 00:00:00 python sendmail

问题描述

仅分别尝试了多个收件人和多个抄送,工作正常,但当我同时尝试这两个时,出现错误:

文件

"pathContinuumanaconda2envsmypythonlibsmtplib.py", 第870行,在Sendmail senderRs[each]=(code,resp)TypeError: 不可散列的类型:‘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()

解决方案

附件Tofrom应为字符串,并且发送邮件应始终采用列表形式。

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

相关文章