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=[""], subject="Some subject", body="Some body", cc=[""])




class scrapy.mail.MailSender(smtphost=None, mailfrom=None, smtpuser=None, smtppass=None, smtpport=None)
  • 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, the MAIL_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.

  • 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




Default: 'scrapy@localhost'

Sender email to use (From: header) for sending emails.


Default: 'localhost'

SMTP host to use for sending emails.


Default: 25

SMTP port to use for sending emails.


Default: None

User to use for SMTP authentication. If disabled no SMTP authentication will be performed.


Default: None

Password to use for SMTP authentication, along with MAIL_USER.


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.


Default: False

Enforce connecting using an SSL encrypted connection