Realizing the function of sending e-mail automatically with Python

Qingben beauty_ How 2021-09-15 03:37:29
realizing function sending e-mail mail


One 、 use python The idea of realizing automatic e-mail is as follows :

Use Python Send E-mail , need Use smtplib And email Two modules
That's what drawing means :
 use python Realize the function of automatically sending e-mail _python Write automatic mail code
in other words email The module is responsible for constructing the e-mail ;smtplib Module is responsible for sending email
SMTP It's an email protocol ,Python Built in right SMTP Support for , You can send plain text mail 、HTML Email and email with attachments .
First , Let's construct a simple email .

# code snippet 
from email.mime.text import MIMEText
import smtplib
msg = MIMEText('hello, Python auto send email', 'plain', 'utf-8')

  • 1.
  • 2.
  • 3.
  • 4.

ad locum , We put email Module and smtplib Modules are introduced , We also use MIMEText Constructed the mail content .
MIMEText In the object , There are three parameters .
 use python Realize the function of automatically sending e-mail _ use python Realize the function of automatically sending e-mail _02
And then through SMTP Send an email out .

Now you have the body of the email , But there is still a lack of , Sender , The recipient ; Next , We collect information from users .

# code snippet 
# Input Email Address and password :
from_addr = input('From: ')
password = input('Password: ')
# Input SMTP Server address :
smtp_server = input('SMTP server: ')
# Enter the recipient's address :
to_addr = input('To: ')

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

ad locum , We need to get , Sender's email , The password of the mailbox , SMTP Server address , And the recipient's email .
This STMP What is the server address ?
SMTP Server address , In fact, it is the address of the proxy transceiver server , It is provided by the mailbox service provider . To put it bluntly , Which company's email do you use , It's the address of which company's email server .

The program written in this paper is QQ Mailbox to test . Use QQ The address of the email server .

QQ mailbox SMTP Server address :smtp.qq.com, port 465, QQ The default port of the mailbox is 25, We use an encrypted port here 465.

Okay , Next, we'll start configuring SMTP Yes .

# code snippet 
server = smtplib.SMTP_SSL(smtp_server, 465) # SMTP The protocol encryption port is 465
server.set_debuglevel(1) # Debug level 
# use set_debuglevel(1) You can print out and SMTP All the information that the server interacts with .

  • 1.
  • 2.
  • 3.
  • 4.

Okay , Next we have to think about sending email , complete SMTP Send mail function

# code snippet 
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())

  • 1.
  • 2.
  • 3.

login() Method is used to log in SMTP The server , There are two parameters , from_addr Is the email address entered by the user , password It's the password for the email .

sendmail() The way to do it is by email , Three parameters need to be introduced :

The first parameter :from_addr Is the sender's email address

The second parameter :[to_addr] Is the email address of the recipient , It's in the form of a list . Because mail can be sent to more than one person at a time , Use list , If you send more than one person , Just write multiple emails , Use commas in the middle .

The third parameter :msg.as_string() Put the email content MIMEText The object becomes str.

Next, let's integrate all the code . as follows :

from email.mime.text import MIMEText
import smtplib
msg = MIMEText('hello, Python auto send email', 'plain', 'utf-8')
# Input Email Address and password :
from_addr = input(' Please enter the sender's email number From: ')
password = input(' Please enter the sender's email password Password: ')
# Input SMTP Server address :
smtp_server = input(' Please enter the email server address SMTP server: ')
# Enter the recipient's address :
to_addr = input(' Please enter the recipient's email address To: ')
server = smtplib.SMTP_SSL(smtp_server, 465) # SMTP The protocol encryption port is 465
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

Okay , Run the above code , Observe the effect in the terminal .
I found the wrong report :SMTPAuthenticationError: (535, b’Login Fail. Please enter your authorization code to login. More information in  http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256’)
If there is such a mistake , It means that there is an authorization problem in the mailbox . That is, the mailbox SMTP The service is not turned on .
For solutions, please refer to : https://blog.51cto.com/u_5839280/3815351
After the problem is solved , Run code , You can receive the message we just sent in the recipient's mailbox Email, Here's the picture

 use python Realize the function of automatically sending e-mail _python Write automatic mail code _03

Take a closer look at the picture above , Will find , There are still two problems : 1. The message has no subject ; 2. The recipient's name is not shown as a friendly name , For example, Mr. so and so ;

This is because of the subject of the email 、 How to display the sender 、 The recipient and other information is not through SMTP The agreement was sent to MTA, It's included in the MTA In the text of , therefore , We have to From、To and Subject Add to MIMEText in , It's a complete email .

Two 、 use python Write the code for automatically sending e-mail as follows :

After perfecting the above code :

# 1、encoders The module is responsible for coding 
# 2、Header The module is responsible for processing mail headers 
# 3、MIMEText The module is responsible for processing text 
# 4、parseaddr Module and formataddr modular Responsible for formatting the input content 
# 5、smtplib Module is responsible for sending email 
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
# Used to process formatted text , Pass the formatted result as a return value 
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr(( Header(name, 'utf-8').encode(), addr))
# Input Email Address and password :
from_addr = input(' Please enter the sender's email number From: ')
password = input(' Please enter the sender's email password Password: ')
# Input SMTP Server address :
smtp_server = input(' Please enter the email server address SMTP server: ')
# Enter the recipient's address :
to_addr = input(' Please enter the recipient's email address To: ')
# The body of the email 
content = ''' dear friend : Hello ! Congratulations on your persistence until now ! Keep working hard, come on , Future period , cheer up ! '''
# hold From、To and Subject Add to MIMEText in , It's a complete email 
# Will be sent to mailbox 、 Receive email 、 Message subject formatting 
msg = MIMEText(content, 'plain', 'utf-8')
msg['From'] = _format_addr(u' Yingzi <%s>' % from_addr)
msg['To'] = _format_addr(u' Administrators <%s>' % to_addr)
msg['Subject'] = Header(u' Greetings from friends ……', 'utf-8').encode()
# SMTP The protocol encryption port is 465
server = smtplib.SMTP_SSL(smtp_server,465)
# Debug level , use set_debuglevel(1) You can print out and SMTP All the information that the server interacts with 
server.set_debuglevel(1)
#login() Method is used to log in SMTP The server , There are two parameters , from_addr Is the email address entered by the user , password It's the password for the email .
server.login(from_addr, password)
#sendmail() The way to do it is by email , Three parameters need to be introduced :
# The first parameter :from_addr Is the sender's email address 
# The second parameter :[to_addr] Is the email address of the recipient , It's in the form of a list . Because mail can be sent to more than one person at a time , Use list , If you send more than one person , Just write multiple emails , Use commas in the middle .
# The third parameter :msg.as_string() Put the email content MIMEText The object becomes str.
server.sendmail(from_addr, [to_addr], msg.as_string())
#server.quit() sentence , After the mail is sent , Stop service means .
server.quit()

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.

The email received is as follows :
 use python Realize the function of automatically sending e-mail _python Write automatic mail code _04

版权声明
本文为[Qingben beauty_ How]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/09/20210909104316832P.html

  1. Python实用小工具之制作酷炫二维码(有界面、附源码)
  2. python链接云服务器的mysql8
  3. [Python] teach you to use selenium to crawl the data of an East moon cake
  4. Python案例实战,pygame模块,Python实现字母代码雨
  5. Python Case Practical, pygame module, Python Implementation letter Code Rain
  6. Mysql8 pour les serveurs Cloud liés Python
  7. 用Python生成二维码
  8. Génération de codes QR en python
  9. Python游戏开发,pygame模块,Python实现乒乓球小游戏
  10. Développement de jeux Python, module pygame, réalisation de jeux de ping - pong Python
  11. Five methods of scheduling jobs in Python
  12. Python and other objects
  13. Pandas之一创建对象
  14. 阿里p7强烈推荐:《Web接口开发与自动化测试:基于Python语言》PDF高清版
  15. Alibaba p7 recommande fortement: développement d'interfaces Web et tests automatisés: basé sur le langage Python PDF HD
  16. 【第2篇】Python爬虫实战-PPT模板素材下载
  17. 【第2篇】Python爬蟲實戰-PPT模板素材下載
  18. [chapitre 2] python crawler Real Game - ppt Template Material Download
  19. 程序员是这样学习【中药学】知识的,先用python采集分析一波
  20. 程序員是這樣學習【中藥學】知識的,先用python采集分析一波
  21. C'est comme ça que les programmeurs apprennent les connaissances de la médecine traditionnelle chinoise, d'abord en utilisant Python pour recueillir et analyser une vague
  22. Python - pydantic(2)嵌套模型
  23. Python - 面向对象编程 - __dict__
  24. Python - 面向对象编程 - 反射 hasattr、getattr、getattr、delattr
  25. Python - 面向对象编程 - 实战(6)
  26. Python - 面向对象编程 - 魔术方法(双下划线方法)
  27. Python - 面向对象编程 - __new__() 和单例模式
  28. Python - 面向对象编程 - __call__()
  29. Python - repr()、str() 的区别
  30. Python - 面向对象编程 - __repr__()
  31. Python - eval()
  32. 用 Django REST framework 来实现一次性验证码(OTP)
  33. Python code checking tool (static code review)
  34. Python QT GUI Design: overview of UI interface visualization components and properties (Fundamentals - 3)
  35. 【算法学习】1863. 找出所有子集的异或总和再求和(java / c / c++ / python / go / rust)
  36. [apprentissage de l'algorithme] 1863. Trouver la somme Xor de tous les sous - ensembles (Java / C / C + + / python / go / Rust)
  37. Python code checking tool (static code review)
  38. Python 万能代码模版:爬虫代码篇
  39. Modèle de code universel Python: Code crawler
  40. 收藏 | Python 之 Pandas系统性总结!
  41. Take you to learn more about nginx basic login authentication: generating passwords using Python
  42. 超硬核Python避坑学习方案奉上!入门到就业一篇就搞定!
  43. Talk about how JMeter executes Python scripts concurrently
  44. Talk about how JMeter executes Python scripts concurrently
  45. Talk about how JMeter executes Python scripts concurrently
  46. python内置函数通过字符串的方式来执行函数代码块,类似java的反射机制相当强大!
  47. python内置函数通过字符串的方式来执行函数代码块,类似java的反射机制相当强大!
  48. python內置函數通過字符串的方式來執行函數代碼塊,類似java的反射機制相當强大!
  49. Les fonctions intégrées Python exécutent des blocs de code de fonction à travers des chaînes, et les mécanismes de réflexion comme Java sont assez puissants!
  50. Python module 1
  51. Python tip: use namedtuple instead of manually created classes
  52. Python - poetry(3)配置项详解
  53. Python - poetry(3)配置项详解
  54. Python - poetry(3)配置項詳解
  55. Python - poetry(3)配置項詳解
  56. Python - détails de l'élément de configuration Poetry (3)
  57. Python - détails de l'élément de configuration Poetry (3)
  58. Python案例实战,pygame模块,Python实现字母代码雨
  59. Python calculation vector angle code
  60. Python基础面试题解读|《Python面试100层》|第1层