Python uses SMTP to send emails

Source: Internet
Author: User

Python uses SMTP to send emails
Python uses SMTP to send emails

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:

    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 = '[email protected]'receivers = ['[email protected]']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 = ["[email protected]"] mail_host = "smtp.XXX.com" # Set server mail_user = "XXX" # username mail_pass = "XXXX" # password mail_postfix = "XXX.com" # The 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'] = '[email protected] 'msg ['from'] =' [email protected] 'msg ['subobject'] = 'Hello world '# 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 = '[email protected]' reciever = '[email protected]' 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"
           

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.