search
HomeBackend DevelopmentPython TutorialDetailed explanation of the process of sending emails using Python's smtplib module

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')

Found return:

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

, 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')

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

(235, 'Authentication successful')

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())

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')

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())

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 id="Hello-It-s-test-email">Hello, It's test email.</h1>")

Statement
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
How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

Define 'array' and 'list' in the context of Python.Define 'array' and 'list' in the context of Python.Apr 24, 2025 pm 03:41 PM

InPython,a"list"isaversatile,mutablesequencethatcanholdmixeddatatypes,whilean"array"isamorememory-efficient,homogeneoussequencerequiringelementsofthesametype.1)Listsareidealfordiversedatastorageandmanipulationduetotheirflexibility

Is a Python list mutable or immutable? What about a Python array?Is a Python list mutable or immutable? What about a Python array?Apr 24, 2025 pm 03:37 PM

Pythonlistsandarraysarebothmutable.1)Listsareflexibleandsupportheterogeneousdatabutarelessmemory-efficient.2)Arraysaremorememory-efficientforhomogeneousdatabutlessversatile,requiringcorrecttypecodeusagetoavoiderrors.

Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools