Home Backend Development Python Tutorial Detailed explanation of the main methods of sending various types of emails in Python

Detailed explanation of the main methods of sending various types of emails in Python

Feb 23, 2017 pm 04:38 PM

The email module in python makes it easier to process emails. This article mainly introduces the main methods of sending various types of emails in python. Those who are interested can learn more.

The email module in python makes it easier to process emails. Today I focus on learning the specific methods of sending emails. I will write down my own experience here and ask experts for some advice.

1. Introduction to related modules

Sending emails mainly uses two modules: smtplib and email. Here is a brief introduction to the two modules:

1. smtplib module

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

SMTP class The constructor represents the connection with the SMTP server. Through this connection, you can send instructions to the SMTP server and perform related operations (such as logging in, sending emails). All parameters are optional.

host: SMTP server host name

port: SMTP service port, the default is 25; if these two parameters are provided when creating the SMTP object, they will be automatically called during initialization connect method to connect to the server.

The smtplib module also provides the SMTP_SSL class and LMTP class, and their operations are basically the same as SMTP.

Methods provided by smtplib.SMTP:

SMTP.set_debuglevel(level): Set whether it is in debug mode. The default is False, which is non-debugging mode, which means no debugging 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 (eg: smpt.yeah.net:25), so there is no need to give the port parameter.

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

SMTP.helo([hostname]): Use the "helo" command to confirm identity to the server. It is equivalent to telling the SMTP server "who I am".

SMTP.has_extn(name): Determine whether the specified name exists in the server mailing list. For security reasons, SMTP servers often block this command.

SMTP.verify(address): Determine whether the specified email address exists in the server. For security reasons, SMTP servers often block this command.

SMTP.login(user, password): Log in to the SMTP server. Almost all SMTP servers now must verify that the user information is legitimate before allowing emails to be sent.

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]): Send mail. Pay attention to the third parameter here. msg is a string representing an email. We know that emails generally consist of a title, sender, recipient, email content, attachments, etc. When sending an email, pay attention to the format of msg. This format is the format defined in the smtp protocol.

SMTP.quit(): Disconnect from the SMTP server, which is equivalent to sending the "quit" command. (smtp.close() is used in many programs. I googled the difference between quit and quit, but I couldn’t find the answer.)

2. Email module

The emial module is used to process email messages, including MIME and other RFC 2822-based message documents. It is very simple to use these modules to define the content of emails. The classes it includes are (more detailed introduction can be found at: http://www.php.cn/):

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

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

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

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

class email.mime.image.MIMEImage (_imagedata[, _subtype[, _encoder[, **_params]]]): MIME binary file object.

class email.mime.message.MIMEMessage(_msg[, _subtype]): A specific message instance. , the usage method is as follows:

msg=mail.Message.Message()  #一个实例 
msg['to']='XXX@XXX.com'   #发送到哪里 
msg['from']='YYY@YYYY.com'    #自己的邮件地址 
msg['date']='2012-3-16'      #时间日期 
msg['subject']='hello world'  #邮件主题
Copy after login

class email.mime.text.MIMEText(_text[, _subtype[, _charset]]): MIME text object, where _ Text is the email content, _subtype email type, which can be text/plain (ordinary text email), html/plain (html email), _charset encoding, which can be gb2312, etc.

2. Several. Specific implementation code of email

1. Ordinary text email

The key to the implementation of sending ordinary text email is to set _subtype in MIMEText to plain. First import smtplib and mimetext. Create an smtplib.smtp instance, connect to the email smtp server, and send it after logging in. The specific code is as follows: (implemented under python2.6)

# -*- coding: UTF-8 -*-
'''
发送txt文本邮件
'''
import smtplib 
from email.mime.text import MIMEText 
mailto_list=[YYY@YYY.com] 
mail_host="smtp.XXX.com" #设置服务器
mail_user="XXXX"  #用户名
mail_pass="XXXXXX"  #口令 
mail_postfix="XXX.com" #发件箱的后缀
 
def send_mail(to_list,sub,content): 
  me="hello"+"<"+mail_user+"@"+mail_postfix+">" 
  msg = MIMEText(content,_subtype=&#39;plain&#39;,_charset=&#39;gb2312&#39;) 
  msg[&#39;Subject&#39;] = sub 
  msg[&#39;From&#39;] = me 
  msg[&#39;To&#39;] = ";".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__ == &#39;__main__&#39;: 
  if send_mail(mailto_list,"hello","hello world!"): 
    print "发送成功" 
  else: 
    print "发送失败"
Copy after login

2. Sending html emails

与text邮件不同之处就是将将MIMEText中_subtype设置为html。具体代码如下:(python2.6下实现)

# -*- coding: utf-8 -*-
&#39;&#39;&#39;
发送html文本邮件
&#39;&#39;&#39;
import smtplib 
from email.mime.text import MIMEText 
mailto_list=["YYY@YYY.com"] 
mail_host="smtp.XXX.com" #设置服务器
mail_user="XXX"  #用户名
mail_pass="XXXX"  #口令 
mail_postfix="XXX.com" #发件箱的后缀
 
def send_mail(to_list,sub,content): #to_list:收件人;sub:主题;content:邮件内容
  me="hello"+"<"+mail_user+"@"+mail_postfix+">"  #这里的hello可以任意设置,收到信后,将按照设置显示
  msg = MIMEText(content,_subtype=&#39;html&#39;,_charset=&#39;gb2312&#39;)  #创建一个实例,这里设置为html格式邮件
  msg[&#39;Subject&#39;] = sub  #设置主题
  msg[&#39;From&#39;] = me 
  msg[&#39;To&#39;] = ";".join(to_list) 
  try: 
    s = smtplib.SMTP() 
    s.connect(mail_host) #连接smtp服务器
    s.login(mail_user,mail_pass) #登陆服务器
    s.sendmail(me, to_list, msg.as_string()) #发送邮件
    s.close() 
    return True 
  except Exception, e: 
    print str(e) 
    return False 
if __name__ == &#39;__main__&#39;: 
  if send_mail(mailto_list,"hello","<a href=&#39;http://www.cnblogs.com/xiaowuyi&#39;>小五义</a>"): 
    print "发送成功" 
  else: 
    print "发送失败"
Copy after login

3、发送带附件的邮件

发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。

# -*- coding: cp936 -*-
&#39;&#39;&#39;
发送带附件邮件
&#39;&#39;&#39;

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

#创建一个带附件的实例
msg = MIMEMultipart()

#构造附件1
att1 = MIMEText(open(&#39;d:\\123.rar&#39;, &#39;rb&#39;).read(), &#39;base64&#39;, &#39;gb2312&#39;)
att1["Content-Type"] = &#39;application/octet-stream&#39;
att1["Content-Disposition"] = &#39;attachment; filename="123.doc"&#39;#这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(att1)

#构造附件2
att2 = MIMEText(open(&#39;d:\\123.txt&#39;, &#39;rb&#39;).read(), &#39;base64&#39;, &#39;gb2312&#39;)
att2["Content-Type"] = &#39;application/octet-stream&#39;
att2["Content-Disposition"] = &#39;attachment; filename="123.txt"&#39;
msg.attach(att2)

#加邮件头
msg[&#39;to&#39;] = &#39;YYY@YYY.com&#39;
msg[&#39;from&#39;] = &#39;XXX@XXX.com&#39;
msg[&#39;subject&#39;] = &#39;hello world&#39;
#发送邮件
try:
  server = smtplib.SMTP()
  server.connect(&#39;smtp.XXX.com&#39;)
  server.login(&#39;XXX&#39;,&#39;XXXXX&#39;)#XXX为用户名,XXXXX为密码
  server.sendmail(msg[&#39;from&#39;], msg[&#39;to&#39;],msg.as_string())
  server.quit()
  print &#39;发送成功&#39;
except Exception, e: 
  print str(e)
Copy after login

4、利用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[&#39;From&#39;] = "XXX@XXX.com"
  msg[&#39;To&#39;] = "YYY@YYY.com"
  msg[&#39;Subject&#39;] = "hello world"


  txt = MIMEText("这是中文的邮件内容哦",&#39;plain&#39;,&#39;gb2312&#39;)   
  msg.attach(txt)
  

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

利用MIMEimage发送图片,原本是想图片能够在正文中显示,可是代码运行后发现,依然是以附件形式发送的,希望有高手能够指点一下,如何可以发送在正文中显示的图片的邮件,就是图片是附件中存在,但同时能显示在正文中,具体形式如下图。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多详解python发送各类邮件的主要方法相关文章请关注PHP中文网!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

See all articles