Python code summary for sending mail using SMTP _python

Source: Internet
Author: User
Tags base64 mixed in python

The SMTP (Simple Mail Transfer Protocol) is simply a mail Transfer protocol, a set of rules for sending messages from the source address to the destination to control how the letters are transferred.
Python's Smtplib provides a convenient way to send e-mail. It is a simple encapsulation of the SMTP protocol.
python creates SMTP object syntax as follows:

Import smtplib
smtpobj = smtplib. SMTP ([host [, Port [, Local_hostname]]])

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

Copy Code code as follows:

Smtp.sendmail (From_addr, To_addrs, msg[, Mail_options, rcpt_options)

Parameter description:
From_addr: Mail Sender address.
To_addrs: List of strings, mailing addresses.
Msg: Sending messages
Here's the third argument, MSG is a string that represents the message. We know that the mail generally by the title, sender, recipient, email content, attachments, etc. constitute, send the message, 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/python

Import smtplib

sender = ' from@fromdomain.com '
receivers = [' to@todomain.com ']

Message = "" "From:from person <from@fromdomain.com>
to:to person <to@todomain.com>
SUBJECT:SMTP E-mail Test this is

a test e-mail message.

"" " 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 messages in HTML format
The difference between sending HTML-formatted messages in Python and sending plain-text messages is to set the _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_ho St= "SMTP. xxx.com "#设置服务器 mail_user=" XXX "#用户名 mail_pass=" XXXX "#口令 mail_postfix=" xxx.com "#发件箱的后缀 def send_mail (To_list,sub,co ntent): #to_list: Recipient; sub: subject; Content: Message contents me= "Hello" + "<" +mail_user+ "@" +mail_postfix+ ">" #这里的hello可以任意设置, after receiving the letter
  , msg = Mimetext (content,_subtype= ' HTML ', _charset= ' gb2312 ') will be displayed as set #创建一个实例, which is set to HTML-formatted mail 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_str ING ()) #发送邮件 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 ' > Small Five Meanings </a>"): Print ("Send Successfully") Else:print ("Send Failed") 

Or you can specify Content-type as text/html in the message body, as follows:

#!/usr/bin/python

Import Smtplib message = ""

"from:from person <from@fromdomain.com>
to:to person & lt;to@todomain.com>
mime-version:1.0
content-type:text/html
subject:smtp HTML e-mail test this

is an e-mail message to was sent in HTML format

<b>this was HTML message.</b>
 
 

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

 Email.mime.text import Mimetext from Email.mime.multipart import mimemultipart Import
Smtplib #创建一个带附件的实例 msg = Mimemultipart () #构造附件1 att1 = 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 to display in the message Msg.attach (ATT1) #构造附件2 att2 = 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 '] = ' 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 ' sends success ' except Exception, E:print (str (e)) 

The

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

#!/usr/bin/python Import smtplib import base64 filename = "/tmp/test.txt" # Read the contents of the file and use the base64 code fo = open (filename, "R B ") Filecontent = Fo.read () encodedcontent = Base64.b64encode (filecontent) # base64 sender = ' webmaster@tutorialpoint.com
' reciever = ' amrood.admin@gmail.com ' marker = ' auniquemarker ' BODY = ' "' This is a test email to send a attachement. "" "# define header information part1 =" "From:from person <me@fromdomain.net> to:to person <amrood.admin@gmail.com> Subject: Sending Attachement mime-version:1.0 content-type:multipart/mixed; boundary=%s--%s "" "% (marker, marker) # define message Action Part2 =" "Content-type:text/plain content-transfer-encoding:8bit%s- -%s "" "% (Body,marker) # defines the nearby part part3 =" "content-type:multipart/mixed; Name=\ "%s\" Content-transfer-encoding:base64 content-disposition:attachment;  filename=%s%s--%s--"" "% (filename, filename, encodedcontent, marker) message = Part1 + part2 + part3 try:smtpobj = Smtplib. SMTP (' localhost ') smtpobj.sendmail (sEnder, Reciever, message) print ("Successfully sent e-mail") except Exception:print ("error:unable to send email") 

If interested friends can continue to refer to the following article.

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.