Home Backend Development Python Tutorial Detailed explanation of the process of sending emails using Python's smtplib module

Detailed explanation of the process of sending emails using Python's smtplib module

Jul 06, 2016 pm 01:29 PM
python smtp smtplib e-mail

1. Log in to the SMTP server
First use the online method (use 163 email here, smtp.163.com is the smtp server address, 25 is the port number):

import smtplib
server = smtplib.SMTP('smtp.163.com', 25)
server.login('j_hao104@163.com', 'password')
Traceback (most recent call last):
 File "C:/python/t.py", line 192, in <module>
  server.login('j_hao104@163.com', 'password')
 File "C:\Python27\lib\smtplib.py", line 622, in login
  raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, 'Error: authentication failed')

Copy after login

Found return:

smtplib.SMTPAuthenticationError: (535, 'Error: authentication failed')
Copy after login

, prompting verification failure.
Some people say that python does not support the SMTP service, or the service is not turned on. But I remembered that the last time I used foxmail to log in to my 163 mailbox, I entered the correct password and it still prompted me that the password was wrong. The final solution is: QQ and 163 mailboxes now have client passwords, use a third-party When logging in, you need to use the client password to log in, and the same is true for Python, so set the client password and then log in with the client password.

2016627144753064.png (700×421)

import smtplib
server = smtplib.SMTP('smtp.163.com', 25)
server.login('j_hao104@163.com', 'clientPassword')
Copy after login

At this point, the login success prompt will be returned:

(235, 'Authentication successful')

Copy after login

2. Send email

First use the code given online:

import smtplib
from email.mime.text import MIMEText
server = smtplib.SMTP('smtp.163.com', 25)
server.login('j_hao104@163.com', 'clientPassword')
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
server.sendmail('j_hao104@163.com', ['946150454@qq.com'], msg.as_string())

Copy after login

When constructing a MIMEText object, the first parameter is the email body, the second parameter is the MIME subtype, and the last parameter is the encoding method.
Sendmail is a method for sending emails. The first parameter is the sending email address, and the second parameter is the recipient email address. It is a list, which means it can be sent to multiple people at the same time. as_string turns the MIMEText object into str.
But the execution result cannot get the result mentioned online:

2016627144839301.jpg (350×162)

Instead:

Traceback (most recent call last):
 File "C:/python/t.py", line 195, in <module>
  server.sendmail('j_hao104@163.com', ['946150454@qq.com'], msg.as_string())
 File "C:\Python27\lib\smtplib.py", line 746, in sendmail
  raise SMTPDataError(code, resp)
smtplib.SMTPDataError: (554, 'DT:SPM 163 smtp11,D8CowEDpDkE427JW_wQIAA--.4996S2 1454562105,please see http://mail.163.com/help/help_spam_16.htm&#63;ip=171.221.144.51&hostid=smtp11&time=1454562105')
Copy after login

After searching online, I found out: smtplib.SMTPDataError: (554, 'DT:SPM 163 smtp11... The error is because the envelope sender and letterhead sender do not match. It can be seen that there is no sending in the picture People and topics, so the code needs to be modified as follows:

import smtplib
from email.header import Header
from email.mime.text import MIMEText
server = smtplib.SMTP('smtp.163.com', 25)
server.login('j_hao104@163.com', 'clientPassword')
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
msg['From'] = 'j_hao104@163.com <j_hao104@163.com>'
msg['Subject'] = Header(u'text', 'utf8').encode()
msg['To'] = u'飞轮海 <jinghao5849312@qq.com>'
server.sendmail('j_hao104@163.com', ['946150454@qq.com'], msg.as_string())
Copy after login

This way you can successfully send the email
The specific information in msg can be tested by sending an email using the normal email method

2016627144903688.png (424×155)

3. Reference example

import smtplib
from email.mime.text import MIMEText

to_list = ['123@123.com', '456@456.com']
server_host = 'smtp.163.com'

username = '你的邮箱账号'
password = '你的邮箱密码'


def send(to_list, sub, content):
  '''
  :param to_list: 收件人邮箱
  :param sub: 邮件标题
  :param content: 内容
  '''
  me = "manager" + "<" + username + ">" 
  # _subtype 可以设为html,默认是plain
  msg = MIMEText(content, _subtype='html')
  msg['Subject'] = sub
  msg['From'] = me
  msg['To'] = ';'.join(to_list)
  try:
    server = smtplib.SMTP()
    server.connect(server_host)
    server.login(username, password)
    server.sendmail(me, to_list, msg.as_string())
    server.close()
  except Exception as e:
    print str(e)

if __name__ == '__main__':
  send(to_list, "这个是一个邮件", "<h1>Hello, It's test email.</h1>")
Copy after login

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks 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 use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

How does PS feathering control the softness of the transition? How does PS feathering control the softness of the transition? Apr 06, 2025 pm 07:33 PM

The key to feather control is to understand its gradual nature. PS itself does not provide the option to directly control the gradient curve, but you can flexibly adjust the radius and gradient softness by multiple feathering, matching masks, and fine selections to achieve a natural transition effect.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to set up PS feathering? How to set up PS feathering? Apr 06, 2025 pm 07:36 PM

PS feathering is an image edge blur effect, which is achieved by weighted average of pixels in the edge area. Setting the feather radius can control the degree of blur, and the larger the value, the more blurred it is. Flexible adjustment of the radius can optimize the effect according to images and needs. For example, using a smaller radius to maintain details when processing character photos, and using a larger radius to create a hazy feeling when processing art works. However, it should be noted that too large the radius can easily lose edge details, and too small the effect will not be obvious. The feathering effect is affected by the image resolution and needs to be adjusted according to image understanding and effect grasp.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

What impact does PS feathering have on image quality? What impact does PS feathering have on image quality? Apr 06, 2025 pm 07:21 PM

PS feathering can lead to loss of image details, reduced color saturation and increased noise. To reduce the impact, it is recommended to use a smaller feather radius, copy the layer and then feather, and carefully compare the image quality before and after feathering. In addition, feathering is not suitable for all cases, and sometimes tools such as masks are more suitable for handling image edges.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

See all articles