Python3 SMTP send mail

Weaving magic demon 2021-01-20 20:28:48
python3 python smtp send mail


SMTP

SMTP(Simple Mail Transfer Protocol) Simple Mail Transfer Protocol , It's a set of rules for sending mail from source to destination , It controls the way letters are transferred .

python Of smtplib Provides a very convenient way to send email . It's right smtp The protocol is simply encapsulated .

One . preparation

Before we code , Get ready first

1. confirm pip edition

install smtplib and email When I was in the library , Check your own pip Is it the highest version of , If not , It is recommended to upgrade to the highest version

2. Email script name

python The name of the email script should never be named email.py

If the command is email.py , In the installation email When I was in the library , Because of the conflict , It's been a mistake

ModuleNotFoundError: No module named 'cStringIO'
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

3. Coding format

The coding format in the lower right corner must be UTF-8, Otherwise, this error will be reported all the time

D:\PycharmProjects\untitled\python\Scripts\python.exe D:/PycharmProjects/python/youjian.py File "D:/PycharmProjects/python/youjian.py", line 2 SyntaxError: Non-UTF-8 code starting with '\xd3' in file D:/PycharmProjects/python/youjian.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details Process finished with exit code 1

resolvent

Creating .py In the bottom right corner of the file, find GBK, take GBK Switch to UTF-8 that will do

4. Turn on SMTP agreement

Log in to your 163 Mailbox and qq mailbox , Turn on SMTP agreement , Here's the picture

163 mailbox
qq mailbox

We need to remember the authorization code for sending email , As shown in the figure below

Authorization code

Two . The code analysis

1. introduce smtplib and email library

import smtplib
from email.header import Header # It's used to set the header and the subject of the message
from email.mime.text import MIMEText # Send a message with only simple text in its body , introduce MIMEText that will do 

2. Define the sender and recipient

sender = 'XXXXXXXXXXXXXXXX@163.com'
receiver = 'XXXXXXXXXXXXX@qq.com'

3. Define the SMTP The server

# Used to send mail SMTP The server
smtpServer = 'smtp.163.com'

4. Define the user name and authorization code for sending e-mail

# Send email user name and authorization code ( It's not the password to log in to the mailbox )
username = 'XXXXXXXXXXXXXXX'
password = 'XXXXXXXXXXXXXXX'

5. Define topics and content

mail_title = ' Test sending email '
mail_body = ' Mail delivery 123'

6. Create an instance

message = MIMEText(mail_body, 'plain', 'utf-8') # Message body
message['From'] = sender # The sender shown on the message
message['To'] = receiver # The recipients shown on the message
message['Subject'] = Header(mail_title, 'utf-8') # Email subject 

7. Create connection , Send E-mail

try:
smtp = smtplib.SMTP() # Create a connection
smtp.connect(smtpServer) # Connect to the sending server
smtp.login(username, password) # logon server
smtp.sendmail(sender, receiver, message.as_string()) # Fill in the message and send
print(" Mail sent successfully !!!")
smtp.quit()
except smtplib.SMTPException:
print(" Failed to send mail !!!")

8. summary

Complete code :

import smtplib
from email.header import Header # It's used to set the header and the subject of the message
from email.mime.text import MIMEText # Send a message with only simple text in its body , introduce MIMEText that will do
# From and to
sender = 'XXXXXXXXXXXXX@163.com'
receiver = 'XXXXXXXXXXX@qq.com'
# Used to send mail SMTP The server
smtpServer = 'smtp.163.com'
# Send email user name and authorization code ( It's not the password to log in to the mailbox )
username = 'XXXXXXXXXXXXXXX'
password = 'XXXXXXXXXXXXXXX'
mail_title = ' Test sending email '
mail_body = ' Mail delivery 123'
# Create an instance
message = MIMEText(mail_body, 'plain', 'utf-8') # Message body
message['From'] = sender # The sender shown on the message
message['To'] = receiver # The recipients shown on the message
message['Subject'] = Header(mail_title, 'utf-8') # Email subject
try:
smtp = smtplib.SMTP() # Create a connection
smtp.connect(smtpServer) # Connect to the sending server
smtp.login(username, password) # logon server
smtp.sendmail(sender, receiver, message.as_string()) # Fill in the message and send
print(" Mail sent successfully !!!")
smtp.quit()
except smtplib.SMTPException:
print(" Failed to send mail !!!")

Execution effect :

Original statement , This article is authorized by the author + Community publication , Unauthorized , Shall not be reproduced .

If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

版权声明
本文为[Weaving magic demon]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/01/20210120183403845h.html

  1. A series of problems and solutions in Java calling Python
  2. python自动化爬取淘宝商品数据导入execl表格
  3. Using Python to automatically punch in the pin / enterprise wechat
  4. 【分享】python+requests接口测试基础
  5. Python automatically crawls Taobao product data and imports it into excel table
  6. C++/Python描述 628. 三个数的最大乘积
  7. Python的容器有哪些?分别有什么作用?
  8. python+requests接口测试基础
  9. 20 行代码:Serverless 架构下用 Python 轻松搞定图像分类和预测
  10. python+requests接口测试基础
  11. [share] Python + requests interface test foundation
  12. C + + / Python description 628. Maximum product of three numbers
  13. What are Python containers and what are their functions?
  14. Testing foundation of Python + requests interface
  15. 20 lines of code: easy to do image classification and prediction with Python under serverless architecture
  16. Python爬取优质高清壁纸网站:彼岸
  17. Testing foundation of Python + requests interface
  18. 【人生苦短,我学 Python】基础篇——列表(Day8)
  19. Python crawls high quality HD Wallpaper website: the other side
  20. Python图像增强与特效-利用百度AI进行黑白图像上色
  21. 【七天搞定Python】day01.Python环境配置、pip、IDE、注释、变量,数据类型、标识符/关键字、输出、输入
  22. Life is short, I learn Python
  23. Python image enhancement and special effects - using Baidu AI to color black and white images
  24. Python environment configuration, Pip, IDE, comment, variable, data type, identifier / keyword, output, input
  25. 为什么说Python是最伟大的语言?看图就知道了 - 知乎
  26. Why is Python the greatest language? Just look at the picture. - Zhihu
  27. 通过创建视频游戏来学习 Python
  28. Learn Python by creating video games
  29. Python3版本下创建计算给定日期范围内工作日方法
  30. Creating a method to calculate working days within a given date range in Python 3
  31. 图解爬虫,用几个最简单的例子带你入门Python爬虫
  32. Graphical crawler, with a few of the simplest examples to take you to the introduction of Python crawler
  33. python+requests基础知识
  34. Basic knowledge of Python + requests
  35. python自定义windowsr日志支持文件分割
  36. python+requests基础知识
  37. Python custom Windowsr log supports file segmentation
  38. Basic knowledge of Python + requests
  39. 高级测试 | Python笔试题
  40. 火了!开源的 Python 抢票神器,过年回家就看这一波了!
  41. Python 爬虫进阶 - 前后端分离有什么了不起,过程超详细!
  42. 【python】使用pip提示ModuleNotFoundError
  43. 【python】虚拟环境搭建
  44. Advanced test | Python written test questions
  45. Fire! Open source Python ticket grabbing artifact, come home to see this wave of New Year!
  46. Python crawler advanced - before and after the end of the separation of what great, super detailed process!
  47. [Python] prompt modulenotfounderror with PIP
  48. Building a virtual environment
  49. Serverless 架构下用 Python 轻松搞定图像分类和预测
  50. Easy image classification and prediction with Python under serverless architecture
  51. python协程爬取某网站的老赖数据
  52. Python coroutine crawls Laolai data of a website
  53. 使用Python分析姿态估计数据集COCO的教程
  54. Using Python to analyze the data set coco of attitude estimation
  55. win环境 python3 flask 上手整理 环境搭建(一)
  56. Getting started with win environment python3 flash
  57. Python实现一个论文下载器,赶紧收藏
  58. win环境 python3 flask 上手整理 快速上手-基础操作(二)
  59. Python 中常见的配置文件写法
  60. Python to achieve a paper Downloader, quickly collect