python Sending Multiple Emails Does Not Show Solutions to Recipient Problems
- 2021-06-29 11:28:38
- OfStack
Background:
In the process of working, we need to monitor the existing machines and services, and notify the corresponding person by mail when there is a problem with the services.
Question:
Send mail using the email library that comes with python 2.7, but the recipient list content is not shown after sending
Example problem code:
# -*- coding:utf-8 -*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email_to(fromAdd, toAdd, subject, html_text, filename):
server = 'mail.****.com'
user = '*****'
password = '********'
strFrom = fromAdd
strTo = toAdd
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = subject
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText(html_text, 'html', 'utf-8')
msgAlternative.attach(msgText)
smtp = smtplib.SMTP()
smtp.connect(server)
smtp.login(user, passwd)
att5 = MIMEText(open(filename, 'rb').read(), 'base64', 'utf-8')
att5["Content-Type"] = 'application/octet-stream'
att5["Content-Disposition"] = 'attachment; filename="fail_7_storage.txt"'
msgRoot.attach(att5)
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
return
Success code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr
from email.utils import formataddr
from email.header import Header
def __format_addr__(addr):
# Resolve mail addresses to ensure aliases are displayed
alias_name, addr = parseaddr(addr)
# Prevent Chinese language problems, transcode and format as str Return
return formataddr((Header(alias_name,charset="utf-8").encode(),
addr.encode("uft-8") if isinstance(addr, unicode) else addr))
def send_email_to(fromAdd, toAdd, subject, html_text, filename=None):
SERVER = 'mail.***.com'
USER = '******'
PASSWD = '***'
strFrom = __format_addr(fromAdd)
strTo = list()
# it turns out to be the case that 1 Pure Mailbox list Now if 1 individual ["jayzhen<jayzhen@jz.com>"] Of list Format for him
try:
for a in toAdd:
strTo.append(__format_addr(a))
except Exception as e:
# Not right a and toadd Conduct type Judgment, error is restored directly
strTo = toAdd
msgRoot = MIMEMultipart('related')
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
# Mail Object
msgText = MIMEText(html_text, 'html', 'utf-8')
msgRoot['Subject'] = Header(subject) # This is the subject of the message, via Header To standardize
msgRoot['From'] = strFrom # The sender is also formatted
msgRoot['to'] = ','.join(strTo) # this 1 If so 1 individual str, Otherwise an error will be made. AttributeError: 'list' object has no attribute 'lstrip' "
msgAlternative.attach(msgText)
smtp = smtplib.SMTP(SERVER, 11)
smtp.set_debuglevel(0)
# smtp.connect(SERVER)
smtp.login(USER, PASSWD)
# Notice here that the fromadd and toAdd and msgRoot['From'] msgRoot['to'] Differences between
smtp.sendmail(fromAdd, toAdd, msgRoot.as_string())
smtp.quit()
Summary:
See msgRoot ['to'] =','.join (strTo) and msgRoot ['to'] = strTo
During the experiment, we found that if this ["to"] 1 was an str, the error would be "AttributeError:'list'object has no attribute'lstrip'"
The data type of ["to"] and sendmail (from_are also found.addrs, to_addrs,...) to_addrs is different;The former is of type str, multiple addresses are separated by commas, and the latter is of type list
There is also the relationship between MIMEText and MIMEMultipart. You can see the source code of 1HA. They are brothers and all inherit MIMEBase. Then it is time to give the attributes ["From"], ["to"] to everyone.