发送email¶
虽然Python通过 smtplib 库使得发送email变得很简单,Scrapy仍然提供了自己的实现。 该功能十分易用,同时由于采用了 Twisted非阻塞式(non-blocking)IO ,其避免了对爬虫的非阻塞式IO的影响。 另外,其也提供了简单的API来发送附件。 通过一些 settings 设置,您可以很简单的进行配置。
简单例子¶
有两种方法可以创建邮件发送器(mail sender)。 您可以通过标准构造器(constructor)创建:
from scrapy.mail import MailSender
mailer = MailSender()
或者您可以传递一个Scrapy设置对象,其会参考 settings:
mailer = MailSender.from_settings(settings)
这是如何来发送邮件了(不包括附件):
mailer.send(to=["someone@example.com"], subject="Some subject", body="Some body", cc=["another@example.com"])
MailSender类参考手册¶
在Scrapy中发送email推荐使用MailSender。其同框架中其他的部分一样,使用了 Twisted非阻塞式(non-blocking)IO 。
-
class
scrapy.mail.
MailSender
(smtphost=None, mailfrom=None, smtpuser=None, smtppass=None, smtpport=None)¶ 参数: - smtphost (str) – 发送email的SMTP主机(host)。如果忽略,则使用
MAIL_HOST
。 - mailfrom (str) – 用于发送email的地址(address)(填入
From:
) 。 如果忽略,则使用MAIL_FROM
。 - smtpuser – SMTP用户。如果忽略,则使用
MAIL_USER
。 如果未给定,则将不会进行SMTP认证(authentication)。 - smtppass (str) – SMTP认证的密码
- smtpport (int) – SMTP连接的短裤
- smtptls – 强制使用STARTTLS
- smtpssl (boolean) – 强制使用SSL连接
-
classmethod
from_settings
(settings)¶ 使用Scrapy设置对象来初始化对象。其会参考 这些Scrapy设置.
参数: settings ( scrapy.settings.Settings
object) – the e-mail recipients
-
send
(to, subject, body, cc=None, attachs=(), mimetype='text/plain')¶ 发送email到给定的接收者。
参数:
- smtphost (str) – 发送email的SMTP主机(host)。如果忽略,则使用
Mail设置¶
这些设置定义了
MailSender
构造器的默认值。其使得在您不编写任何一行代码的情况下,为您的项目配置实现email通知的功能。