Python code summary for sending mail using SMTP

Source: Internet
Author: User
Tags format message
Python's Smtplib provides a convenient way to send e-mails. It is a simple encapsulation of the SMTP protocol, the need for friends can refer to the following

The SMTP (Simple Mail Transfer Protocol) is simply the message Transfer Protocol, which is a set of rules for sending mail from the source address to the destination, and it controls the way the letters are relayed.
Python's Smtplib provides a convenient way to send e-mails. It provides a simple encapsulation of the SMTP protocol.
Python creates SMTP object syntax as follows:

Import smtplibsmtpobj = Smtplib. SMTP ([host [, Port [, Local_hostname]])

Parameter description:
HOST:SMTP Server host. You can specify the IP address of the host or the domain name such as: w3cschool.cc, which is an optional parameter.
PORT: If you provide the host parameter, you need to specify the port number that the SMTP service uses, and the SMTP port number is typically 25.
Local_hostname: If SMTP is on your local computer, you only need to specify the server address as localhost.
The Python SMTP object uses the SendMail method to send the message with the following syntax:

Smtp.sendmail (From_addr, To_addrs, msg[, Mail_options, Rcpt_options]

Parameter description:

From_addr: Mail Sender address.

To_addrs: String list, mailing address.

Msg: Send Message

Notice here that the third parameter, MSG, is a string that represents the message. We know that the mail is generally composed of the title, sender, recipient, mail content, attachments, etc., when sending mail, pay attention to the format of MSG. This format is the format defined in the SMTP protocol.

Instance

Here's a simple example of sending a message using Python:

#!/usr/bin/pythonimport smtplibsender = ' from@fromdomain.com ' receivers = [' to@todomain.com ']message = ' "" From:from Person <from@fromdomain.com>to:to person <to@todomain.com>subject:smtp e-mail testthis is a test e-mail mess Age. "" " Try:  smtpobj = Smtplib. SMTP (' localhost ')  smtpobj.sendmail (sender, receivers, message)       print "successfully sent email" except Smtpexception:  print "error:unable to send Email"

Use Python to send HTML-formatted messages
Python sends HTML-formatted messages differently than messages that send plain text messages by setting _subtype in Mimetext to HTML. The specific code is as follows:


Import smtplib from Email.mime.text import mimetext mailto_list=["YYY@YYY.com"] mail_host= "SMTP. xxx.com "#设置服务器mail_user =" XXX "  #用户名mail_pass =" XXXX "  #口令 mail_postfix=" xxx.com "#发件箱的后缀 def send_mail (to_ list,sub,content): #to_list: Recipient; sub: subject; Content: Message contents  me= "Hello" + "<" +mail_user+ "@" +mail_postfix+ ">"  #这里的hello可以任意设置, after receiving the letter, will follow the settings shown  msg = mimetext (content,_subtype= ' HTML ', _charset= ' gb2312 ')  #创建一个实例, This is set to HTML format message  msg[' Subject ' = Sub  #设置主题  msg[' from '] = Me   msg[' to '] = ";". Join (To_list)   try:     s = smtplib. SMTP ()     s.connect (mail_host) #连接smtp服务器    s.login (mail_user,mail_pass) #登陆服务器    s.sendmail (Me, To_list, Msg.as_string ()) #发送邮件    s.close ()     return True   except Exception, E:     print str (e)     return False if __name__ = = ' __main__ ':   if Send_mail (mailto_list, "Hello", "<a href= ' Http://www.cnblogs.com/xiaowuyi ' > Little Wu Yi </a> "):     print (" Send Success ")  else:     print (" Send Failed ")

Alternatively, you can specify Content-type as text/html in the message body, as in the following example:


#!/usr/bin/pythonimport smtplibmessage = "" "From:from person <from@fromdomain.com>to:to person < TO@TODOMAIN.COM>MIME-VERSION:1.0CONTENT-TYPE:TEXT/HTMLSUBJECT:SMTP HTML e-mail testthis is an e-mail message to be s ENT in HTML format<b>this are HTML message.</b>

Python sends a message with an attachment
To send a message with an attachment, you first create an instance of Mimemultipart (), and then construct the attachment, which, if there are multiple attachments, can be constructed in turn and then sent using SMTPLIB.SMTP.


from email.mime.text import mimetextfrom email.mime.multipart import Mimemultipartimport smtplib# create an instance with an attachment msg = Mimemultipart () #构造附件1att1 = mimetext (open (' D:\\123.rar ', ' RB '). Read (), ' base64 ', ' gb2312 ') att1["Content-type"] = ' Application/octet-stream ' att1["content-disposition"] = ' attachment; Filename= "123.doc" #这里的filename可以任意写, what name to write, what name is displayed in the message Msg.attach (ATT1) #构造附件2att2 = mimetext (open (' D:\\123.txt ', ' RB '). Read (), ' base64 ', ' gb2312 ') att2["content-type"] = ' application/octet-stream ' att2[' content-disposition '] = ' Attachment Filename= "123.txt" ' Msg.attach (ATT2) #加邮件头msg [' to '] = ' YYY@YYY.com ' msg[' from '] = ' XXX@XXX.com ' msg[' subject '] = ' Hello ' World ' #发送邮件try: Server = Smtplib. SMTP () server.connect (' SMTP.  XXX.com ') server.login (' XXX ', ' XXXXX ') #XXX为用户名, XXXXX for password server.sendmail (msg[' from '), msg[' to '],msg.as_string ()) Server.quit () print ' sent successfully ' except Exception, E:print (str (e)) 

The following instance specifies the Content-type header as Multipart/mixed and sends a/tmp/test.txt text file:


#!/usr/bin/pythonimport smtplibimport base64filename = "/tmp/test.txt" # reads the contents of the file and uses base64 encoding fo = open (filename, "RB") Filecontent = Fo.read () encodedcontent = Base64.b64encode (filecontent) # base64sender = ' webmaster@tutorialpoint.com ' reciever = ' amrood.admin@gmail.com ' marker = "auniquemarker" BODY = "" "This is a test e-mail to the send an attachement." " # define Header information part1 = "" From:from person <me@fromdomain.net>to:to person <amrood.admin@gmail.com>subject: Sending attachementmime-version:1.0content-type:multipart/mixed; boundary=%s--%s "" "% (marker, marker) # define message Action Part2 =" "content-type:text/plaincontent-transfer-encoding:8bit%s--%s" "% (Body,marker) # defines the nearby part part3 =" "" content-type:multipart/mixed; Name=\ "%s\" content-transfer-encoding:base64content-disposition:attachment; filename=%s%s--%s--"" "% (filename, filename, encodedcontent, marker) message = Part1 + part2 + part3try:smtpobj = smtplib . SMTP (' localhost ') smtpobj.sendmail (sender, reciever, message) print ("Successfully senT email ") except Exception:print (" error:unable to send email ") 

"Recommended"

1. Detailed description Python uses SMTP to send mail instances

2. Share Python to implement SMTP send message graphics instances

3. C # call QQ mailbox SMTP send mail modified version code

4. Python sends mail using SMTP

5. PHP smtp Send mail

6. Python SMTP Mail module detailed

7. Python smtplib module sends SSL/TLS secure message instances

  • 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.