Send e-mail to multiple CC and multiple TO recipients simultaneously using python

落爺英雄遲暮 提交于 2020-01-16 11:11:20

问题


Tried with only multiple to and multiple cc individually, which works fine but when i try both i get an error:

File

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

Code:

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:


Attaching To or from should be a string and sendmail should always be in the form of the list.

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



回答2:


The to parameter should be a list of all the addresses you wish to send the message to. The division in To: and Cc: is basically for display purposes only; SMTP simply has a single sequence of recipients which translate to one RCPT TO command for each address.

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


来源:https://stackoverflow.com/questions/49062924/send-e-mail-to-multiple-cc-and-multiple-to-recipients-simultaneously-using-pytho

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!