python_014 SMTP e-mail

Source: Internet
Author: User
Tags base64

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 = ' [email protected] ' receivers = [' [email protected] ']message = ' "" From:from Perso n <[email protected]>to:to person <[email protected]>subject:smtp e-mail testthis is a test e-mail message. " "" Try:smtpobj = Smtplib. SMTP (' localhost ') smtpobj.sendmail (sender, receivers, message) print "successfully sent email" except Smtpexce Ption:print "error:unable to send Email"
Send HTML-formatted messages

python Send HTML-formatted messages with messages that send plain text messages specific code is as follows:

Import smtplib  from email.mime.text import mimetext  mailto_list=["[ Email protected] "] 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, the     msg = mimetext will be displayed according to the settings (content,_ Subtype= ' HTML ', _charset= ' gb2312 ')      #创建一个实例, here set to HTML format mail     msg[' Subject '] = sub     #设置主题     msg[' from '] = me       msg[' to '] =  ";". Join (to_list)       try:           s = smtplib. SMTP () &nbsP;         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 ' > Xiao Wu yi </a>"):           print  "Send Success"        else:          print  "Send Failed" 

or you You can also specify Content-type as text/html in the body of the message, The following example:

#!/usr/bin/pythonimport smtplibmessage = "" "From:from person <[email protected]>to:to person <[email protected ]>SUBJECT:SMTP HTML e-mail testthis is an e-mail message to being sent in HTML format<b>this is HTML message.</b >
Send a message with an attachment

send a message with an attachment, first create a mimemultipart () instance, and then construct the attachment, If you have more than one attachment, you can construct it sequentially, and finally send it with 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 is written, what name is displayed in the message Msg.attach (ATT1) #构造附件2att2  = mimetext (' 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 '] =  ' [email  Protected] ' msg[' from '] =  ' [email protected] ' msg[' subject '] =  ' Hello world ' # Send mail try:    server = smtplib. SMTP ()     server.connect (' SMTP. XXX.com ')     seRver.login (' XXX ', ' XXXXX ') #XXX为用户名, XXXXX for the password     server.sendmail (msg[' from '], msg[' to '], Msg.as_string ())     server.quit ()     print  ' send Success ' except  Exception, e:      print str (e)

The following instance specifies Content-type header for multipart/ Mixed, and send the/tmp/test.txt text file:

#!/usr/bin/pythonimport smtplibimport base64filename =  "/tmp/test.txt" #  read the contents of the file and use  base64  Code Fo = open (filename,  "RB") Filecontent = fo.read () sender =   ' [email protected] ' reciever =  ' [email protected] ' marker =  ' AUNIQUEMARKER ' Body = "" "This is a test email to send an attachement" "" " #  Defining header information part1 =  "" "From: from person <[email protected]>to: to  Person <[email protected]>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) #  definition near 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 "

python_014 SMTP e-mail

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.