The text and pictures in this article come from the network, only for learning, exchange, do not have any commercial purposes, copyright belongs to the original author, if you have any questions, please contact us to deal with

The following article comes from Tencent Cloud author: Call me Long

(Want to learn Python? Python Learning exchange group: 1039649593, to meet your needs, materials have been uploaded to the group file stream, you can download! There is also a huge amount of new 2020Python learning material.) If a Python crawler fails, you want to notify yourself as soon as possible, by email.

Email protocol is SMTP,Python built-in support for SMTP, can send plain text mail, HTML mail, and mail with attachments,Python support for SMTP has two modules smtplib and email, Emial is responsible for the construction of mail, smtplib is responsible for sending mail.

Here, I use email box 163 to send emails, enable SMTP function, and use email server smtp.163.com of 163

Construct plain text messages

# MSG = MIMEText(' HTTP 403', 'plain', 'UTF-8 ')
Copy the code

The MIMEText object takes three arguments.

  • The body of the email,
  • The MIME type is plain for plain text and HTML for web pages.
  • Set the mail format, here color UTF-8 to ensure compatibility with multiple languages.

Construct web mail.

msg = MIMEText('< HTML > < body > < h1 > hello < / h1 > < p > abnormal page < a href = "http://www.baidu.com" > baidu < / a > < p > < / body > < / HTML >'.'html'.'utf-8')
Copy the code

Complete email code

# coding:utf-8


from email.header import Header

from email.mime.text import MIMEText

from email.utils import parseaddr, formataddr


import smtplib


def _format_addr(s) :

    name, addr = parseaddr(s)

    return formataddr((Header(name, 'utf-8').encode(), addr))


# sender address

from_addr = '******@163.com'    Change this to your email address


# Email password

password = '* * * * * * *'    Change this to your email password.



# Addressee address

to_addr = '******@126.com'    # Addressee address. I use 126 mailbox here, and I found that QQ mailbox was rejected.



# 163 Address of the NetEase mail server

smtp_server = 'smtp.163.com'



# Set email information

# MSG = MIMEText(' HTTP 403', 'plain', 'UTF-8 ')



msg = MIMEText('< HTML > < body > < h1 > hello < / h1 > < p > abnormal page < a href = "http://www.baidu.com" > baidu < / a > < p > < / body > < / HTML >'.'html'.'utf-8')

msg['from'] = _format_addr('Python Green channel <%s>' % from_addr)

msg['to'] = _format_addr('Python Green Channel Manager <%s>' % to_addr)

msg['subject'] = Header('Python Green channel crawler Running Status'.'utf-8').encode()



# Send email

server = smtplib.SMTP(smtp_server, 25)

server.login(from_addr, password)

server.sendmail(from_addr, [to_addr], msg.as_string())

server.quit()
Copy the code