Explain the main ways python sends all kinds of emails

  • 2020-05-19 05:03:57
  • OfStack

The email module in python makes it easier to deal with emails. Today, I focused on the specific ways of sending emails. Here, I will write my own experience and ask the master to give me some advice.

1. Introduction of related modules

Two modules, smtplib and email, are mainly used in sending emails. Here, a brief introduction is made to the two modules:

1. smtplib module

smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])

The SMTP class constructor, which represents the connection to the SMTP server, through which instructions can be sent to the smtp server to perform relevant operations (e.g., login, send mail). All parameters are optional.

host: smtp server hostname

port: port for smtp service, default is 25; If these two parameters are provided when the SMTP object is created, the connect method is automatically called to connect to the server during initialization.

The smtplib module also provides the SMTP_SSL class and LMTP class, which operate on SMTP base 1.

Methods provided by smtplib.SMTP:

SMTP.set_debuglevel (level) : sets whether to be in debug mode. The default is False, or non-debug mode, which means no debug information is output.

SMTP.connect ([host[, port]]) : connect to the specified smtp server. The parameters represent the smpt host and port, respectively. Note: you can also specify the port number in the host parameter (e.g., smpt.yeah.net :25), so there is no need to give the port parameter.

SMTP.docmd (cmd[, argstring]) : sends instructions to the smtp server. The optional parameter argstring represents the parameter of the instruction.

SMTP.helo ([hostname]) : confirm identity to the server using the "helo" directive. This is equivalent to telling the smtp server "who I am."

SMTP.has_extn (name) : determines whether the specified name exists on the server mailing list. For security reasons, smtp servers often block this instruction.

SMTP.verify (address) : determines whether the specified mail address exists on the server. For security reasons, the smtp server often blocks this instruction.

SMTP.login (user, password) : log in to smtp server. Almost all smtp servers now have to verify that user information is valid before allowing email.

SMTP.sendmail (from_addr, to_addrs, msg[, mail_options, rcpt_options]) : send an email. Note here that the third parameter 1, msg, is a string representing the message. We know that email 1 usually consists of subject line, sender, recipient, content, attachment, etc. When sending email, please pay attention to the format of msg. This format is the format defined in the smtp protocol.

SMTP.quit () : disconnect from the smtp server, equivalent to sending the "quit" command. (smtp.close () is used in many programs, and the difference between quit and google is 1, but there is no answer.)

2. email module

The emial module is used to process mail messages, including MIME and other RFC 2822 based message documents. Using these modules to define the content of the message is straightforward. Which include class has (more detail visible: http: / / docs python. org library/email. mime. html) :

class email. mime. base. MIMEBase (_maintype _subtype, * * _params) : this is MIME a base class. There is generally no need to create an instance at use. Where _maintype is the content type, such as text or image. _subtype is the minor type type of content, such as plain or gif. **_params is a dictionary that is passed directly to Message.add_header ().

class email. mime. multipart. MIMEMultipart ([_subtype [, boundary [, _subparts [, _params]]]] : a subclass of MIMEBase, multiple MIME collections of objects, a default value for mixed _subtype. boundary is the boundary of MIMEMultipart, and the default boundary is countable.

class email. mime. application. MIMEApplication (_data [, _subtype [, _encoder * * _params [,]]]] : MIMEMultipart a subclass.

class email.mime.audio.MIMEAudio (_audiodata[, _subtype[, _encoder[, **_params]]]) : MIME audio object

class email. mime. image. MIMEImage (_imagedata [, _subtype [, _encoder * * _params [,]]]] : MIME2 hexadecimal file object.

class email. mime. message. MIMEMessage (_msg [_subtype]) : specific instances of a message, using method is as follows:


msg=mail.Message.Message()  #1 An instance  
msg['to']='XXX@XXX.com'   # Where to send it  
msg['from']='YYY@YYYY.com'    # Your own email address  
msg['date']='2012-3-16'      # Time to date  
msg['subject']='hello world'  # Email subject  

class email. mime. text. MIMEText (_text [, _subtype [, _charset]]) : MIME text object, which is _text mail content, _subtype mail type, can be text/plain (plain text E-mail), html/plain (html mail), _charset code, can be gb2312 and so on.

2. Several kinds of mail implementation code

1. Plain text messages

The key to the implementation of plain text mail is to set _subtype in MIMEText to plain. First import smtplib and mimetext. Create smtplib.smtp instance, connect mail smtp server, login send, the specific code is as follows :(python2.6)


# -*- coding: UTF-8 -*-
'''
 send txt Text messages 
'''
import smtplib 
from email.mime.text import MIMEText 
mailto_list=[YYY@YYY.com] 
mail_host="smtp.XXX.com" # Setup server 
mail_user="XXXX"  # The user name 
mail_pass="XXXXXX"  # password  
mail_postfix="XXX.com" # The suffix of the outbox 
 
def send_mail(to_list,sub,content): 
  me="hello"+"<"+mail_user+"@"+mail_postfix+">" 
  msg = MIMEText(content,_subtype='plain',_charset='gb2312') 
  msg['Subject'] = sub 
  msg['From'] = me 
  msg['To'] = ";".join(to_list) 
  try: 
    server = smtplib.SMTP() 
    server.connect(mail_host) 
    server.login(mail_user,mail_pass) 
    server.sendmail(me, to_list, msg.as_string()) 
    server.close() 
    return True 
  except Exception, e: 
    print str(e) 
    return False 
if __name__ == '__main__': 
  if send_mail(mailto_list,"hello","hello world ! "): 
    print " Send a success " 
  else: 
    print " Send failure " 

2. Sending html emails

The difference from text mail is that _subtype in MIMEText is set to html. The specific code is as follows :(implementation under python2.6)


# -*- coding: utf-8 -*-
'''
 send html Text messages 
'''
import smtplib 
from email.mime.text import MIMEText 
mailto_list=["YYY@YYY.com"] 
mail_host="smtp.XXX.com" # Setup server 
mail_user="XXX"  # The user name 
mail_pass="XXXX"  # password  
mail_postfix="XXX.com" # The suffix of the outbox 
 
def send_mail(to_list,sub,content): #to_list : addressee; sub : theme; content : email content 
  me="hello"+"<"+mail_user+"@"+mail_postfix+">"  # Here, hello It can be set arbitrarily. After receiving the letter, it will be displayed according to the Settings 
  msg = MIMEText(content,_subtype='html',_charset='gb2312')  # create 1 I'm going to set it to zero html Format of the mail 
  msg['Subject'] = sub  # Set the theme 
  msg['From'] = me 
  msg['To'] = ";".join(to_list) 
  try: 
    s = smtplib.SMTP() 
    s.connect(mail_host) # The connection smtp The server 
    s.login(mail_user,mail_pass) # Login server 
    s.sendmail(me, to_list, msg.as_string()) # Send E-mail 
    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 5 The righteous </a>"): 
    print " Send a success " 
  else: 
    print " Send failure " 

3. Send email with attachments

To send a message with an attachment, first create an instance of MIMEMultipart(), then construct the attachment, if there are more than one, and finally send it using smtplib.smtp.


# -*- coding: cp936 -*-
'''
 Send email with attachments 
'''

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

# create 1 Two instances with attachments 
msg = MIMEMultipart()

# Construction accessories 1
att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="123.doc"'# Here, filename You can write whatever you want, what name to put, what name to display in the email 
msg.attach(att1)

# Construction accessories 2
att2 = 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 header 
msg['to'] = 'YYY@YYY.com'
msg['from'] = 'XXX@XXX.com'
msg['subject'] = 'hello world'
# Send E-mail 
try:
  server = smtplib.SMTP()
  server.connect('smtp.XXX.com')
  server.login('XXX','XXXXX')#XXX Is the user name, XXXXX For the password 
  server.sendmail(msg['from'], msg['to'],msg.as_string())
  server.quit()
  print ' Send a success '
except Exception, e: 
  print str(e) 

4. Send pictures using MIMEimage


# -*- coding: cp936 -*-
import smtplib
import mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

def AutoSendMail():
  msg = MIMEMultipart()
  msg['From'] = "XXX@XXX.com"
  msg['To'] = "YYY@YYY.com"
  msg['Subject'] = "hello world"


  txt = MIMEText(" This is the email in Chinese ",'plain','gb2312')   
  msg.attach(txt)
  

  file1 = "C:\\hello.jpg"
  image = MIMEImage(open(file1,'rb').read())
  image.add_header('Content-ID','<image1>')
  msg.attach(image)
  
  
  server = smtplib.SMTP()
  server.connect('smtp.XXX.com')
  server.login('XXX','XXXXXX')
  server.sendmail(msg['From'],msg['To'],msg.as_string())
  server.quit()
  
if __name__ == "__main__":
  AutoSendMail()

Using MIMEimage sending pictures, was meant to picture can be displayed in the text, but the code after the operation found that still send in the form of attachment, l hope to have ace to give directions, how can send mail in the text shown in the picture, there is picture is in the attachment, but at the same time can be displayed in the text, concrete form below.


Related articles: