Python group mail instance code

  • 2020-04-02 13:20:23
  • OfStack

It goes straight to the code


import smtplib
msg = MIMEMultipart()
# Construction accessories 1
att1 = MIMEText(open('/home/a2bgeek/develop/python/hello.py', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="hello.txt"'# Here, filename You can write whatever you want, what's the name, what's the name in the message 
msg.attach(att1)
# Construction accessories 2
#att2 = MIMEText(open('/home/a2bgeek/develop/python/mail.py', 'rb').read(), 'base64', 'gb2312')
#att2["Content-Type"] = 'application/octet-stream'
#att2["Content-Disposition"] = 'attachment; filename="123.txt"'
#msg.attach(att2)
# Add header 
strTo = ['XXX1@139.com', 'XXX2@163.com', 'XXX3@126.com']
msg['to']=','.join(strTo)
msg['from'] = 'YYY@163.com'
msg['subject'] = ' Email subject '
# Send E-mail 
try:
    server = smtplib.SMTP()
    server.connect('smtp.163.com')
    server.login('YYY@163.com','yourpasswd')
    server.sendmail(msg['from'], strTo ,msg.as_string())
    server.quit()
    print ' Send a success '
except Exception, e:
    print str(e)

Careful readers will find the following sentence in the code: MSG ['to']=','.join(strTo), but MSG [['to'] is not used later.

The problem is that smtp.sendmail and email.mimetext need two different things.

Email. MIMEText sets up the "To:" the header for the body of the E-mail. It is ONLY 2 for displaying a result To the human being at the other end, and the like all E-mail headers, Must be a single string. (Note that it does not actually have to have anything to do with the people who actually received the message.)

SMTP. Sendmail, on the other hand, sets up the "envelope" of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.

So, what you need to do is COMBINE the two replies you receiled.set MSG 'to' to a single string, but pass the raw list to sendmail.

Okay, that's it for today.


Related articles: