SoFunction
Updated on 2024-11-12

python send mail sample code (Python2/3 can be used directly)

Send regular mail

Send text and html normal emails as follows:

from  import Header
from  import MIMEText
from  import parseaddr, formataddr

import smtplib

def _format_addr(s):
  name, addr = parseaddr(s)
  return formataddr((Header(name, 'utf-8').encode(), addr))

def get_server(username):
  """
  Get email server by email address
  :param username:username, for example:123456@
  :return: mailbox server address, you can add it according to your actual business, for example:
  """
  servers = {'qq' : ''
        , '126' : 'smtp.'
        , '163' : 'smtp.'
        , '139' : 'smtp.'}

  for key,value in ():
    if key in username:
      return value

def send_mail(username, password, to, sender_name, subject, content, email_type):
  """
  :param username.
  :param password.
  :param to: list of recipients []
  :param sender_name.
  :param subject: :param content.
  :param content: :param email_type: :param
  :param email_type.
  :return.
  """
  from_addr = username
  password = password
  to_addr = to
  smtp_server = get_server(username)

  # The body of the message is of type MIMEText
  msg = MIMEText('%s'%(content), '%s'%(email_type), 'utf-8')
  msg['From'] = _format_addr('%s<%s>' % (sender_name, from_addr))
  msg['To'] = _format_addr('<%s>' % to_addr)
  msg['Subject'] = Header('%s'%(subject), 'utf-8').encode()

  # Port 25 for normal login, port 465 with ssl authentication
  # smtp_server = ''
  # server = smtplib.SMTP_SSL(smtp_server, 465)
  server = (smtp_server, 25)
  server.set_debuglevel(1)
  (from_addr, password)
  (from_addr, to_addr, msg.as_string())
  ()

if __name__ == '__main__':
  """Send Simple Text Mail"""
  username = '******@'
  password = '******'
  sender_name = '******@'
  subject = 'test mail'
  content = '<html><h1>ikeguang present letter</h1></html> <a href="" rel="external nofollow" ></a></html>'
  # email_type value: plain, text type email; html, html type email
  email_type = 'html'
  _to = ['******@', '******@']
  for to in _to:
    send_mail(username, password, to, sender_name, subject, content, email_type)
    print('send mail to %s success' % to)

Sending emails with attachments

def send_mail_multipart(username, password, to, sender_name, subject, content, email_type):
  from_addr = username
  password = password
  to_addr = to
  smtp_server = get_server(username)

  msg = MIMEMultipart()
  # The body of the message is of type MIMEText
  (MIMEText('%s'%(content), '%s'%(email_type), 'utf-8'))
  msg['From'] = _format_addr('%s<%s>' % (sender_name, from_addr))
  msg['To'] = _format_addr('<%s>' % to_addr)
  msg['Subject'] = Header('%s'%(subject), 'utf-8').encode()

  # Reading attachments
  filename = 'D:/My Documents/Codes/PyCode/source/image/'
  with open(filename, 'rb') as f:
    # Set the MIME and filename of the attachment, in this case the png type.
    mime = MIMEBase('image', 'jpg', filename='')
    # With the necessary header information.
    mime.add_header('Content-Disposition', 'attachment', filename='')
    mime.add_header('Content-ID', '<0>')
    mime.add_header('X-Attachment-Id', '0')
    # Read in the contents of the attachment: #
    mime.set_payload(())
    # Encoded in Base64.
    encoders.encode_base64(mime)
    # Added to MIMEMultipart.
    (mime)

  # Port 25 for normal login, port 465 with ssl authentication
  # smtplib.SMTP_SSL(smtp_server, 465)
  server = (smtp_server, 25)
  server.set_debuglevel(1)
  (from_addr, password)
  (from_addr, [to_addr], msg.as_string())
  ()