Scrapy – 发送电子邮件
先决条件: Scrapy
Scrapy提供了自己的发送电子邮件的工具,非常好用,它是使用 Twisted 非阻塞 IO 实现的,以避免干扰爬虫的非阻塞 IO。本文讨论如何使用scrapy 发送邮件。
对于这个 MailSender 类需要从scrapy 导入,然后需要调用具有正确参数的专用函数才能成功发送邮件。
使用的功能
- MailSender() 用于设置邮件程序。
Syntax:
classscrapy.mail.MailSender(smtphost=None, mailfrom=None, smtpuser=None, smtppass=None, smtpport=None)
Parameters
- smtphost (str or bytes) – the SMTP host to use for sending the emails.
- mailfrom (str) – the address used to send emails (in the From: header).
- smtpuser – the SMTP user. If omitted, the MAIL_USER setting will be used. If not given, no SMTP authentication is going to be performed..
- smtppass (str or bytes) – the SMTP pass for authentication.
- smtpport (int) – the SMTP port to connect to
- smtptls (bool) – enforce using SMTP STARTTLS
- smtpssl (bool) – enforce employing a secure SSL connection
- classmethodfrom_settings() 实例化一个 Scrapy 设置对象,它可以尊重这些 Scrapy 设置。
Syntax:
classmethodfrom_settings(settings)
Parameters
- settings (scrapy.settings.Settings object) – the e-mail recipients
- send() 向给定的收件人发送电子邮件。
Syntax:
send(to, subject, body, cc=None, attachs=(), mimetype=’text/plain’, charset=None)
Parameters
- to (str or list) –the e-mail recipients as a string or as an inventory of string
- subject (str) – the subject of the e-mail
- cc (str or list) – the e-mails to CC as a string or as an inventory of strings
- body (str) – the e-mail body
- attachs (collections.abc.Iterable) – an iterable of tuples (attach_name, mimetype, file_object) where attach_name is a string with the name that will appear on the e-mail’s attachment, mimetype is the mimetype of the attachment and file_object may be a readable file object with the contents of the attachment
- charset (str) – the character encoding to use for the e-mail contents
方法
- 导入模块
- 设置邮件程序
- 添加邮件的主题和正文
- 提供发送者和接收者的电子邮件地址
- 发邮件
例子:
Python3
# import module
from scrapy.mail import MailSender
# setup mailer
mailer = MailSender(mailfrom="Something@gmail.com",
smtphost="smtp.gmail.com", smtpport=465, smtppass="MySecretPassword")
# send mail
mailer.send(to=["abc@gmail.com"], subject="Scrapy Mail",
body="Hi ! GeeksForGeeks", cc=["another@example.com"])
输出: