Python sends multiple attachments and email implementations that support HTML and plain text content

Source: Internet
Author: User
Tags server port

Due to the frequent need to send and receive e-mail, such as daily (week) Work reports, test reports, monitoring alarms, timing reminders and so on, most of the e-mail sent in the form. This article will implement a Python e-mail sending class that supports the ability to send multiple attachments (directories), HTML or plain text content, CC recipients, multiple recipients, and more.


Code implementation

#!/usr/bin/env python#-*-coding:utf-8-*-"Copyright (C) by Thomas Hu. All rights reserved. @author: Thomas hu@version:1.0@created:2015-05-17 "Import base64import httplibimport reimport OSI Mport smtplibfrom xml.etree Import elementtreefrom email.utils import formatdatefrom email. Mimetext Import mimetextfrom Email. Mimebase Import mimebasefrom Email. Mimemultipart Import mimemultipartfrom Email import encodersclass Emailsender (object): Def __init__ (self, smtp_server,        Smtp_port=0, Verbose=false, debug_level=1, encoding= "Utf-8"): "Initiate the Emailsender.        @param smtp_server:the Email SMTP server.        @param smtp_port:the Email SMTP Server port, if use the default port (+), you can set it to 0 or 25.        @param verbose:show The processing information if set to ' True ', and default is ' False '.        @param debug_level:set The Smtplib debug level, if it ' s ' 0 ', would enable debug information. @param encoding:the encoding or CharSet for EMAIL body text or attachment file name, default is "Utf-8". "' Self.server = smtp_server self.port = Int (smtp_port) self.verbose = verbose Self.debug_lev el = Int (debug_level) self.encoding = Encoding self.attachments = [] #Create SMTP Instance SEL F.SMTP = Smtplib.  SMTP (Self.server, Self.port) self.smtp.set_debuglevel (self.debug_level) self.print_verbose ("Init SMTP server Successfully. server=%s, port=%d. "% (        Self.server, Self.port)) def print_verbose (self, message): "Print the verbose information.        @param message:the message to being print if the verbose is "True". "If Self.verbose:print (message) def login (self, user, password):" ' Login to S        MTP server.        @param user:the user name of the email sender.        @param password:the Passord of the user for login to SMTP server. ' self.from_addr = user + ' @ ' + '. '. Join (self.seRver.split (".")        [1:]) Try:self.print_verbose ("Start to login into SMTP server.server=%s, port=%d."% ( Self.server, Self.port)) self.smtp.login (user, password) self.print_verbose ("Login into SMTP server        Successfully. ") Except Exception as Ex:print ("Login into SMTP server failed! Error Info:%s "% (str (ex))) def __add_attachment_file (self, filename, encoding, Filter):" ' Add attachment file t        o the attachment list.        @param filename:the file name of attachment, should not is a path.        @param encoding:the encode of the attachment file name.        @param filter:the file Filter object, must implement ' accept (filename) ' interface, and return True or False. "# Check If the file is acceptable by the filter if filter is not NONE:TRY:AC                cept = filter.accept (filename) except:accept = False if Accept = = false: RetUrn # Add The attachment to the attachment list try:basename = os.path.basename (filename)            Attach = Mimebase ("Application", "Octet-stream") attach.set_payload (open (filename, "RB"). Read ()) #attach. Add_header ("Content-disposition", "attachment;filename=%s"% (basename)) Attach.add_header ("Content-dis Position "," attachment ", filename= (Encoding," ", basename)) encoders.encode_base64 (attach) Self.atta Chments.append (Attach) self.print_verbose ("Add attachment \"%s\ "successfully."% ( filename) except Exception as Ex:print ("Add attachment file \"%s\ "failed.) Error Info:%s. "% ( filename, str (ex))) def add_attachment (self, path, Encoding=none, Filter=none): "' Add attachmen        T file to the attachment list. @param path:the path of files to be added as attachment files.        If is a directory, any of the files in it would be added. @param EncodinG:the encode of the attachment file name.        @param filter:the file Filter object, must implement ' accept (filename) ' interface, and return True or False. "If not os.path.exists (path): Self.print_verbose (" warning:attachment path \ "%s\" was not exists. "% ( Path)) Return charset = Encoding if (encoding is not None) else self.encoding if Os.path.isfile (p            ATH): Return self.__add_attachment_file (Path, CharSet, Filter) for root, dirs, files in Os.walk (path): For f in files:fname = Os.path.join (root, f) self.__add_attachment_file (fname, CH Arset, Filter) def send_email (self, subject, To_addrs, Cc_addrs, content, subtype= "plain", Charset=none        ): "Send the email to the receivers."        @param subject:the Email ' s subject (title). @param to_addrs:the Receivers ' addresses, it's a list looks like ["[Email protected]_server.com]," [email&Nbsp;protected]_server.com "].        @param cc_addrs:the Copy to receivers ' addresses, with the same format as To_addrs. @param content:the Email message body, it can be plain text or HTML text, which depends on the parameter ' Content_Type        '.        @param subtype:the content Type, it can be "html" or "plain", and default is "plain".  @param charset:the CharSet of message content, default is ' None ', use the same encoding as the initial function, which        Default is "Utf-8".        @return: If send successfully, return ' True ', otherwise, return ' False '. "' CharSet = CharSet if CharSet is not None of else self.encoding #Set the root information msg _root = Mimemultipart ("related") msg_root["Subject"] = Subject msg_root["from"] = self.from_addr # can Change it to any string msg_root["to"] = ",". Join (To_addrs) msg_root["CC"] = ",". Join (Cc_addrs) Msg_r oot["Date"] = FormatDate (localtime=true) mSg_root.preamble = "This was a multi-part message in MIME format."  #Encapsulate the plain and HTML of the message body into a ' alternative ' part, #so message agents can decide which        They want to display.  Msg_alt = Mimemultipart ("alternative") #Set the message content msg_txt = mimetext (content, Subtype.lower (),        CharSet) Msg_alt.attach (msg_txt) #Add The alternative part-to-root part. Msg_root.attach (Msg_alt) #Add the attachment files for attach in Self.attachments:msg_root.attac        H (Attach) #Extend the copy to addresses to To_addrs To_addrs.extend (Cc_addrs) #Send the email Try:self.smtp.sendmail (Self.from_addr, To_addrs, msg_root.as_string ()) self.print_verbose ("Send EMA        Il successfully. ") Except Exception as Ex:print ("Send email failed. Error info:%s "% (str (ex))) return False return True def close (self):" ' Quit FRom the SMTP.        ' Self.smtp.quit () self.print_verbose ("Logout SMTP server successfully.")     def test (): Smtp_server = "smtp.163.com" user = "yyy" password = "yyyxxx" from_addr = "[email protected]" To_addrs = ["[email protected]"] Cc_addrs = [] Subject = "Email sending test" content = ' Dear friends,&lt    ;p/><a href= "HTTP://BLOG.CSDN.NET/THOMASHTQ" > Welcome to my csdn blog!</a> <p/>thanks a lot! ' Attach_files=[r "D:\temp\sendemail\attach"] Emailsender = Emailsender (Smtp_server, verbose=true) emailsender.login (U SER, password) for attach in Attach_files:emailsender.add_attachment (Attach, "Utf-8") emailsender.send_email (Subject, To_addrs, Cc_addrs, content, subtype= "html", charset= "Utf-8") emailsender.close () if __name__ = = ' __ma In__ ': Test ()


The code has a detailed explanation, please forgive me in English comments ah, accustomed to ^_^. At run time, modify the associated user name, password, server, recipient, attachment list, and so on in the test () function. That is the code at the beginning of the test () function (before the empty line), and it is OK to modify it according to your own circumstances.

Python sends multiple attachments and email implementations that support HTML and plain text content

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.