SoFunction
Updated on 2024-11-12

Based on python SMTP to realize the automatic sending of mail tutorial analysis

Recently, a project in the work needs to automatically send some information mail to the specified mailbox needs, then how to realize Python automatically send mail function? Next we will briefly introduce how to use Python to realize the function of automatically sending mail.

Python SMTP Send Mail

SMTP (Simple Mail Transfer Protocol) that is, simple mail transfer protocol , to put it bluntly, is the protocol for sending mail , python's smplib library on the SMTP protocol for a simple package , provides support for SMTP , you can send plain-text mail , HTML files and mail with attachments .

First we build a SendEmailManager class, also following the idea of object-oriented programming to do, the general structure is as follows:

class SendEmailManager(object):

  def __init__(self, **kwargs):
    # Initialization parameters
    ...

  def _get_conf(self, key):
    # Get configuration parameters
    ...

  def _init_conf(self):
    # Initialize configuration parameters
    ...

  def _login_email(self):
    # Login to mailbox server
    ...
  def _make_mail_msg(self):
    # Build text mail objects
    ...

  def do_send_mail(self):
    # Mail delivery
    ...

def __init__(self, **kwargs)

The initialization function of the class can be used to set the properties of the object and give the initial value, which can be a parameter or a fixed value, in which the parameter **kwargs is a variable keyword parameter dictionary will be passed to the function of the real parameter, here we are mainly on the SMTP server (here using qq mailbox), the proxy mailbox to send emails, in the mailbox set in the client's authorization password, the variable parameters for the some initialization. The specific code is as follows:

# SMTP server, here to use qq mailbox, other mailboxes on their own Baidu
EMAIL_HOST = ''
# Proxy mailboxes for sending mail
EMAIL_HOST_USER = 'xxxx@'
# In the mailbox set in the client authorization password, note that this is not the mailbox password, how to get the mailbox authorization code, please see this article last tutorial
EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxx'
def __init__(self, **kwargs):
  # Initialization parameters
  self.email_host = EMAIL_HOST
  self.email_host_user = EMAIL_HOST_USER
  self.email_host_pass = EMAIL_HOST_PASSWORD
   = kwargs

def _get_conf(self, key)

It is mainly responsible for reading the value of the variable parameter dictionary through the key for use by other functions.

def _get_conf(self, key):
  # Get configuration parameters
  value = (key)
  if key != "attach_file_list" and (value is None or value == ''):
    raise Exception("configuration parameter '%s' cannot be empty" % key)
  return value

def _init_conf(self)

This function is mainly responsible for initializing the configuration parameters returned by function _get_conf so that the next function can call the relevant configuration parameters.

def _init_conf(self):
  # Initialize configuration parameters
  print(self._get_conf('receives'))
   = self._get_conf('receives')
  self.msg_subject = self._get_conf('msg_subject')
  self.msg_content = self._get_conf('msg_content')
  self.msg_from = self._get_conf('msg_from')
  # attachment
  self.attach_file_list = self._get_conf('attach_file_list')

def _login_email(self)

Log in to the mail server, I'm here to log in to the qq mailbox server, port number 465, other mailbox port number, please Baidu, the code is as follows:

def _login_email(self):
  # Login to mailbox server
  try:
    server = smtplib.SMTP_SSL(self.email_host, port=465)
    # set_debuglevel(1) prints out all information about the interaction with the SMTP server
    server.set_debuglevel(1)
    # Login Mailbox
    (self.email_host_user, self.email_host_pass)
    return server
  except Exception as e:
    print("mail login exception:", e)
    raise e

def _make_mail_msg(self)

This function builds a mail instance object to handle the content of the mail. A normal e-mail generally has the sender and receiver information, the subject of the e-mail, the body of the e-mail, some e-mails also have attachments, the specific settings see the following code:

def _make_mail_msg(self):
  # Build the mail object
  msg = MIMEMultipart()
  (MIMEText(self.msg_content, 'plain', 'utf-8'))
  # Subject of the e-mail
  msg['Subject'] = Header(self.msg_subject, "utf-8")
  # Sender mailbox information
  msg['From'] = "<%s>" % self.msg_from
  # msg['From'] = Header(self.msg_from + "<%s>" % self.email_host_user, "utf-8")
  msg['To'] = ",".join()
  print("---", self.attach_file_list)
  if self.attach_file_list:
    for i, att in enumerate(self.attach_file_list):
      # Construct attachments to transfer files in the current directory
      if not att:
        break
      att_i = MIMEText(open(att, 'rb').read(), 'base64', 'utf-8')
      att_i["Content-Type"] = 'application/octet-stream'
      # The filename here can be whatever you want it to be, and it will be displayed in the email.
      att_i["Content-Disposition"] = 'attachment; filename="%s"' % att
      (att_i)
  return msg

def do_send_mail(self)

To send an email is to string together the last few functions and go straight to the code:

def do_send_mail(self):
  # Mail delivery
  try:
    self._init_conf()
    server = self._login_email()
    msg = self._make_mail_msg()
    (self.email_host_user, , msg.as_string())
    ()
    print("Sent successfully!")
  except Exception as e:
    print("Mail delivery exception", e)

Configure the parameters and test if you can send emails normally:

if __name__ == "__main__":
  mail_conf = {
    'msg_from': 'xxxx@', # Address of the sender of the e-mail
    'receives': ['xxxx@', 'xxxxxxxx@', ], # the address of the recipient of the message, this is a list as there may be more than one recipient of the message
    'msg_subject': 'Python automated email test!!!', # Subject of the e-mail
    'msg_content': 'Life is short, I use python!!!', # The content of the e-mail
    'attach_file_list': {"test_file1.py": "", "test_file2.pem": "./"}, # is a list of paths to attached files, also a list, can also not have this one
  }

  manager = SendEmailManager(**mail_conf)
  manager.do_send_mail()


ok, sent successfully, and adding attachments was no problem.

Beginning we speak of obtaining the authorization code of the client mailbox, the tutorial is as follows (qq mailbox as an example):

Okay, goal accomplished.

This is the whole content of this article.