Python code summary for sending emails using SMTP

Source: Internet
Author: User
Python's smtplib provides a convenient way to send emails. It encapsulates the smtp protocol in a simple way. if you need it, you can refer to python's smtplib to provide a convenient way to send emails. It encapsulates the smtp protocol. For more information, see

SMTP (Simple Mail Transfer Protocol) is a Simple Mail Transfer Protocol. it is a set of rules used to send Mail from the source address to the destination address, which controls the Transfer mode of Mail.
Python's smtplib provides a convenient way to send emails. It encapsulates the smtp protocol.
The syntax for creating an SMTP object in Python is as follows:

import smtplibsmtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Parameter description:
Host: SMTP server host. You can specify the IP address or domain name of the host, for example, w3cschool. cc. this is an optional parameter.
Port: if you provide the host parameter, you must specify the port number used by the SMTP service. Generally, the SMTP port number is 25.
Local_hostname: if SMTP is on your local machine, you only need to specify the server address as localhost.
The Python SMTP object uses the sendmail method to send emails. The syntax is as follows:


The code is as follows:


SMTP. sendmail (from_addr, to_addrs, msg [, mail_options, rcpt_options]

Parameter description:
From_addr: email sender address.
To_addrs: string list, Mail sending address.
Msg: send messages
Note that the third parameter, msg is a string, indicating the mail. We know that an email generally consists of the title, sender, recipient, email content, attachments, etc. when sending an email, pay attention to the msg format. This format is defined in the smtp protocol.
Instance
The following is a simple example of sending emails using Python:

#!/usr/bin/pythonimport smtplibsender = 'from@fromdomain.com'receivers = ['to@todomain.com']message = """From: From Person 
 
  To: To Person 
  
   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 SMTPException:  print "Error: unable to send email"
  
 

Use Python to send HTML emails
The difference between sending an HTML-format email in Python and sending a plain text message is to set _ subtype in MIMEText to html. The code is as follows:

Import smtplib from email. mime. text import MIMEText mailto_list = ["YYY@YYY.com"] mail_host = "smtp.XXX.com" # set server mail_user = "XXX" # Username mail_pass = "XXXX" # Password mail_postfix = "XXX.com" # sender's suffix def send_mail (to_list, sub, content): # to_list: recipient; sub: topic; content: mail content me = "hello" + "<" + mail_user + "@" + mail_postfix + ">" # Here, hello can be set at will. after receiving the mail, msg = MIMEText (content, _ subtype = 'html', _ charset = 'gb2312 ') # create an instance according to the settings, here, the message msg ['subobject'] = sub # sets the topic msg ['from'] = me msg ['to'] = ";". join (to_list) try: s = smtplib. SMTP () s. connect (mail_host) # connect to the smtp server s. login (mail_user, mail_pass) # log on to the server s. sendmail (me, to_list, msg. as_string () # send email s. close () return True expect T Exception, e: print str (e) return False if _ name _ = '_ main _': if send_mail (mailto_list, "hello", "Xiao Wuyi"): print ("sent successfully") else: print ("failed to send ")

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

#!/usr/bin/pythonimport smtplibmessage = """From: From Person 
 
  To: To Person 
  
   MIME-Version: 1.0Content-type: text/htmlSubject: SMTP HTML e-mail testThis is an e-mail message to be sent in HTML format
   This is HTML message.This is headline."""try:  smtpObj = smtplib.SMTP('localhost')  smtpObj.sendmail(sender, receivers, message)       print("Successfully sent email")except SMTPException:  print("Error: unable to send email")
  
 

Python sends emails with attachments
To send an email with an attachment, you must first create a MIMEMultipart () instance, and then construct the attachment. if there are multiple attachments, you can construct them in sequence, and finally use smtplib. smtp to send the email.

From email. mime. text import MIMETextfrom email. mime. multipart import MIMEMultipartimport smtplib # Create an instance with an attachment msg = MIMEMultipart () # construct the attachment 1att1 = MIMEText (open ('d: \ 123.rar ', 'RB '). read (), 'base64', 'gb2312') att1 ["Content-Type"] = 'application/octet-stream' att1 ["Content-Disposition"] = 'attachment; filename = "123.doc" '# Here, the filename can be written at will, what name is written, and what name is displayed in the email msg. attach (att1) # construct the attachment 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) # add the mail header msg ['to'] = 'yyy @ YYY.com 'msg ['from'] = 'XXX @ XXX.com' msg ['subobject'] = 'Hello world '# send email try: server = smtplib. SMTP () server. connect ('smtp .XXX.com ') server. login ('XXX', 'xxxxx') # XXX is the user name, and XXXXX is the password server. sendmail (msg ['from'], msg ['to'], msg. as_string () server. quit () print 'sent successfully 'failed t Exception, e: print (str (e ))

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

#! /Usr/bin/pythonimport smtplibimport base64filename = "/tmp/test.txt" # read the file content and use 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 email to send an attachement. "# define the header information part1 =" From: From Person
 
  
To: To Person Subject: Sending AttachementMIME-Version: 1.0Content-Type: multipart/mixed; boundary = % s -- % s "% (marker, marker) # define the message action part2 = "Content-Type: text/plainContent-Transfer-Encoding: 8bit % s -- % s" % (body, marker) # define nearby parts of part3 = "Content-Type: multipart/mixed; name = \" % s \ "Content-Transfer-Encoding: base64Content-Disposition: attachment; filename = % s -- "% (filename, filename, encodedcontent, marker) message = part1 + part2 + part3try: smtpObj = smtplib. SMTP ('localhost') smtpObj. sendmail (sender, reciever, message) print ("Successfully sent email") failed t Exception: print ("Error: unable to send email ")
 

For more articles about the code summary of sending emails using SMTP in Python, refer to PHP Chinese network!

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.