Python: An Example of automatically sending mails to multiple users, sending mails, and adding multiple attachments.
1. Recently, some of the company's data statistics and analysis reports are regularly sent to the mailbox of relevant personnel every day. The configuration code has been manually deleted and needs to be restored, since it was too cumbersome to use shell configuration for sending in linux, it was intended to use python to implement this function. However, it was found that all the documents on the Internet were not sorted out and the code was not well written, for example, the sender can only send the previous email address, and the attachments cannot be written flexibly.
Main problems:
1. smtplib. SMTPAuthenticationError: (550, B 'user has no permission ')
2. smtplib. SMTPAuthenticationError: (535, B 'Error: authentication failed ')
These two errors are caused by your password not an authorization code. The authorization code is generated by Baidu.
3. 554 DT: SPM 163 smtp5
This is caused by a bounce detection mechanism in NetEase mail, which seems to be related to frequent sending. I encountered it when I resend it until I added a Netease mailbox as the inbox, I don't know if this is the cause. The specific cause is unknown. If anyone knows this, please inform me in a private letter or comment. Thank you !!
Prepare to view the python version number on the system:
It indicates that it has been installed.
2. The implementation code is as follows (this is to edit the test code under IDEL on Windows, and only change the attachment path on linux)
#-*-Coding: UTF-8-*-from email import encodersimport osimport tracebackfrom email. header import Headerfrom email. mime. text import MIMETextfrom email. utils import parseaddr, formataddrimport smtplibfrom email. mime. multipart import MIMEMultipartfrom email. mime. base import MIMEBasefrom email import encoders # Chinese processing def _ format_addr (s): name, addr = parseaddr (s) return formataddr (Header (name, 'utf-8 '). Encode (), addr) def send_email (to_addr_in, filepath_in ): # configure "from_addr = '******** @ 163.com' smtp_server = 'smtp .163.com 'password =' ******** 'for the mail sender and recipient # This is the password of the third-party authorized client in your mailbox, not your logon password to_addr = to_addr_in to_addrs = to_addr.split (',') msg = MIMEMultipart () msg ['from'] = _ format_addr ('python enthusiast <% s> '% from_addr) # displayed sender # msg ['to'] = _ format_addr ('administrator <% s> '% to_addr) # msg ['to'] = ", ". join (_ Addrs) # multiple recipients msg ['subobject'] = Header ('greetings from SMTP ...... ', 'Utf-8 '). encode () # displayed mail title # path to be passed in # filepath = r 'd: \ test 'filepath = filepath_in r = OS. path. exists (filepath) if r is False: msg. attach (MIMEText ('no file... ', 'plain', 'utf-8') else: # The Mail body is MIMEText: msg. attach (MIMEText ('send with file... ', 'plain', 'utf-8') # traverse the specified directory and display all file names under the directory pathDir = OS. listdir (filepath) for allDir in pathDir: child = OS. path. join (filepath, allDir) print child. decode ('gbk ')#. decode ('gbk') is used to solve the problem of garbled characters in Chinese characters # adding an attachment is to add a MIMEBase to read a local file with open (child, 'rb') as f: # Set the MIME and file name of the attachment. Here the txt type is: mime = MIMEBase ('file', 'xls ', filename = allDir) # Add the necessary header information: mime. add_header ('content-disposition', 'attachment', filename = allDir) mime. add_header ('content-id', '<0>') mime. add_header ('x-Attachment-id', '0') # Read the content of the Attachment: mime. set_payload (f. read () # encoded in Base64: encoders. encode_base64 (mime) # Add to MIMEMultipart: msg. attach (mime) try: server = smtplib. SMTP (smtp_server, 25) # server. starttls () server. set_debuglevel (1) # used to display the execution steps of mail sending server. login (from_addr, password) # print to_addrs server. sendmail (from_addr, to_addrs, msg. as_string () server. quit () failed t Exception, e: print "Error: unable to send email" print traceback. format_exc () if _ name _ = '_ main _': send_email ('******* @ qq.com, * ***** @ 163.com ', 'd: \ test ')
3. The execution result in PyCharm is as follows:
It indicates that the email has been sent successfully. You can view it in the corresponding email address. The attachment text exists in the corresponding folder.
If no attachment text exists (this is Netease mail, the above QQ mailbox indicates that both mailboxes have received the email ):
The above example of using python to automatically send emails to multiple users, send mails, and add multiple attachments is all the content shared by Alibaba Cloud. I hope to give you a reference and support for the customer's home.