Python for SMTP mail delivery

Source: Internet
Author: User
Always wanted to add mail to the framework, so organize under the Python mail send function

First Python is a mail -enabled send, a built-in SMTP library, a message that supports sending plain text, HTML, and adding attachments . After the mailbox, such as 163, QQ, Sina and other mailboxes by default to turn off the SMTP service, we need to open manually, open, through the sender's mailbox, authorization password through the sender's SMTP service sent

The code is as follows:

#!/usr/bin/env python#-*-coding:utf_8-*-from email.mime.text import mimetextfrom email.mime.multipart import Mimemult Ipartfrom email.mime.multipart Import mimebasefrom Email import encodersfrom email.header import Headerfrom email.utils i Mport parseaddr, formataddrimport smtplibclass sendemail:outbox = "pythondldysl01@163.com" # Outbox Address Password = "wxqcl25825 8 "# Authorization password is not a mailbox login password inbox =" xxx@qq.com "# Inbox Address Smtp_server =" smtp.163.com "# Outbox server Address Def __init__ (self): pass @classmet Hod def _format_address (CLS, text): name, address = parseaddr (text) return formataddr (Header (name, "Utf-8"). Encode (), ad Dress)) @classmethod def send_email_text (CLS): msg = Mimetext ("Test SMTP mail Send function", "plain", "Utf-8") # first parameter: Message body # Second argument: message type Plain Text # Third parameter: encoded msg["from"] = sendemail._format_address ("a message from 163 <%s>"% sendemail.outbox) # Sender name with outbox address msg["to" ] = sendemail._format_address ("admin <%s>"% sendemail.inbox) # Recipient name with inbox address msg["Subject"] = Header ("Greetings from SMTP", "UTF -8 "). Encode () # message header Try:seRVer = Smtplib. SMTP (Sendemail.smtp_server, 25) # Constructs SMTP server connection # Server.set_debuglevel (1) # Debug output mode default off Server.login (Sendemail.outbo X, Sendemail.password) # Log on to the SMTP server Server.sendmail (Sendemail.outbox, [Sendemail.inbox], msg.as_string ()) # Send mail server . Quit () print "Mail sent successfully" except Exception, E:print str (e) Print "message sent Failed" if __name__ = = ' __main__ ': Sendemail.send_emai L_text ()

This is just plain text content, can support HTML format content, modify the content as follows:

msg = Mimetext ("Test SMTP mail Send function", "plain", "utf-8")

Content changed to HTML format, "plain" to "HTML"

Finally, the message that added the attachment

The code is as follows:

@classmethod def Send_email_multipart (CLS): msg = Mimemultipart () msg["from"] = Sendemail._format_address ("An e-mail from 163 & Lt;%s> "% sendemail.outbox) # Sender name with outbox address msg[" to "] = sendemail._format_address (" admin <%s> "% sendemail.inbox) # Close The name of the person and the Inbox address msg["Subject"] = Header ("Greetings from SMTP", "Utf-8"). Encode () # message header Msg.attach (Mimetext ("Test the SMTP mail sending feature for adding attachments", " Plain "," Utf-8 ")) with open (" E:\\work\\python project\\createproject\\20160421140953.xml "," RB ") as F: # Sets the mime and file name of the attachment m IME = mimebase ("xml", "xml", filename= "test report. xml") # plus the necessary header information Mime.add_header (' content-disposition ', ' attachment ', filen Ame= "test report. xml") Mime.add_header (' Content-id ', ' <0> ') mime.add_header (' X-attachment-id ', ' 0 ') # reads the contents of the attachment in: MIME. Set_payload (F.read ()) # with BASE64 encoding: Encoders.encode_base64 (MIME) # Add to MIMEMultipart:msg.attach (MIME) try:server = SM Tplib. SMTP (Sendemail.smtp_server, 25) # Constructs SMTP server connection # Server.set_debuglevel (1) # Debug output mode default off Server.login (Sendemail.outbo X, Sendemail.password) # login SMTP Server Server.sendmail (Sendemail.outbox, [Sendemail.inbox], msg.as_string ()) # Send mail server.quit () print "Mail sent successfully" except Exception, E:print str (e) print "Mail Send Failed"


The above is the Python mail delivery function of the specific implementation code, I hope that everyone's learning is helpful.

Related Article

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.