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

WBOY
Release: 2016-07-06 13:29:43
Original
2354 people have browsed it

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template