Q: Scrapy MailSender結合Gmail發送郵件
在Scrapy網頁爬蟲框架中,想要實作發送電子郵件的功能,可以使用內建的MailSender模組(Module),透過基本的設定即可達成。開啟Scrapy專案的settings.py設定檔,加入以下的Gmail SMTP設定:
MAIL_HOST = "smtp.gmail.com"
MAIL_PORT = 587
MAIL_FROM = "申請Gmail應用程式密碼所使用的電子郵件帳號"
MAIL_PASS = "Gmail應用程式密碼"
MAIL_TLS = True
ITEM_PIPELINES = {
'news_scraper.pipelines.CsvPipeline': 500,
}
設定完成後,開啟ITEM PIPELINE資料模型管道(pipelines.py)檔案,引用Scrapy框架的設定檔及MailSender模組(Module),如下範例:
from itemadapter import ItemAdapter
from news_scraper import settings
from scrapy.mail import MailSender
接著,在CsvPipeline類別(Class)的close_spider()方法(Method)中,來建立Scrapy MailSender物件,以及指定Gmail的附件,包含「附件顯示的名稱(attach_name)」、「網際網路媒體類型(mime_type)」及「檔案物件(file_object)」,如下範例:
class CsvPipeline:
...
def close_spider(self, spider):
self.exporter.finish_exporting()
self.file.close()
mail = MailSender(smtphost=settings.MAIL_HOST,
smtpport=settings.MAIL_PORT,
smtpuser=settings.MAIL_FROM,
smtppass=settings.MAIL_PASS,
smtptls=settings.MAIL_TLS)
attach_name = "posts.csv"
mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
file_object = open("posts.csv", "rb")
return mail.send(to=["example@gmail.com"],
subject="news",
body="",
attachs=[(attach_name, mime_type, file_object)])
)網站觀看更多精彩內容。