Sending e-mail¶
虽然Python通过 smtplib库使得发送email变得很简单,Scrapy仍然提供了自己的实现, 该功能十分易用,同时由于采用了Twisted非阻塞式IO ,其避免了对爬虫的非阻塞式IO的影响。It also provides a simple API for sending attachments and it’s very easy to configure, with a few settings.
简单例子¶
There are two ways to instantiate the mail sender. You can instantiate it using the standard constructor:
from scrapy.mail import MailSender
mailer = MailSender()
Or you can instantiate it passing a Scrapy settings object, which will respect the settings:
mailer = MailSender.from_settings(settings)
And here is how to use it to send an e-mail (without attachments):
mailer.send(to=["someone@example.com"], subject="Some subject", body="Some body", cc=["another@example.com"])
注
如上面的示例中所示,to
和cc
需要电子邮件地址的列表,不是单一的地址,即使只有一个收件人,即to="someone@example.com"
将无法工作。
MailSender类参考¶
在Scrapy中发送email推荐使用MailSender。其同框架中其他的部分一样,使用了Twisted非阻塞式IO 。
- class
scrapy.mail.
MailSender
(smtphost=None, mailfrom=None, smtpuser=None, smtppass=None, smtpport=None)¶ Parameters: - smtphost (str) – the SMTP host to use for sending the emails. If omitted, the
MAIL_HOST
setting will be used. - mailfrom (str) – the address used to send emails (in the
From:
header). If omitted, theMAIL_FROM
setting will be used. - smtpuser – the SMTP user. If omitted, the
MAIL_USER
setting will be used. If not given, no SMTP authentication will be performed. - smtppass (str) – the SMTP pass for authentication.
- smtpport (int) – the SMTP port to connect to
- smtptls (boolean) – 强制使用SMTP STARTTLS
- smtpssl (boolean) – enforce using a secure SSL connection
- classmethod
from_settings
(settings)¶ Instantiate using a Scrapy settings object, which will respect these Scrapy settings.
Parameters: settings ( scrapy.settings.Settings
object) – the e-mail recipients
-
send
(to, subject, body, cc=None, attachs=(), mimetype='text/plain', charset=None)¶ Send email to the given recipients.
Parameters: - to (list) – the e-mail recipients
- subject (str) – the subject of the e-mail
- cc (list) – the e-mails to CC
- body (str) – the e-mail body
- attachs (iterable) – 一个由元组
(attach_name, mimetype, file_object)
组成的可迭代对象,其中attach_name
是出现在电子邮件附件中的名字字符串,mimetype
是附件的MIME类型,file_object
是一个包含附件内容的可读文件对象。 - mimetype (str) – the MIME type of the e-mail
- charset (str) – the character encoding to use for the e-mail contents
- smtphost (str) – the SMTP host to use for sending the emails. If omitted, the
Mail设置¶
这些设置定义MailSender
构造函数的默认值,而且可以用来配置你的项目中的邮件通知功能,而不需要(为那些使用MailSender
的扩展和代码)编写任何代码。
MAIL_USER¶
Default: None
User to use for SMTP authentication. If disabled no SMTP authentication will be performed.
MAIL_TLS¶
Default: False
Enforce using STARTTLS. STARTTLS is a way to take an existing insecure connection, and upgrade it to a secure connection using SSL/TLS.