2017-01-02 2 views
0

Jinja2PremailerをScrapy拡張機能として使用して電子メールを作成して送信する方法の例がありますか?Scene拡張子としてJinja2を使用して電子メールを送信する方法

私はそれらをScrapyで使用すべきではない場合、高度な電子メールを送信するために他のHTMLテンプレートソリューションをお勧めしますか?

+0

なぜ彼らがスクレイピーで作業する必要があるのですか? – eLRuLL

答えて

1

あなたは間違いなくScrapyjinja2でメールを送信できます。私たちは常にスクレイパーから警告を受けるようにしています。 mandrillを使用して電子メールを送信しますが、他のSMTPプロバイダを使用して電子メールを送信することができます。また、premailerをテンプレートに実装するようにこのコードを拡張することもできます。

import requests 
from scrapy import signals 
from jinja2 import Environment, PackageLoader 

class EmailExt(object): 
    """ 
    Email extension for scrapy 
    """ 

    @classmethod 
    def from_crawler(cls, crawler): 
     """ 
     On `spider_closed` signal call `self.spider_closed()` 
     """ 
     ext = cls() 
     crawler.signals.connect(ext.spider_closed, 
           signal=signals.spider_closed) 
     return ext 

    def spider_closed(self, spider, reason): 

     #initialize `PackageLoader` with the directory to look for HTML templates 
     env = Environment(loader=PackageLoader('templates', 'emails')) 

     template = env.get_template("email-template.html") 

     # render template with the custom variables in your jinja2 template 
     html = template.render(title="Email from scraper", count=10) 

     # send the email using the mandrill API 
     requests.post('https://api.mailgun.net/v3/yourcompany/messages', 
         auth=('api', 'API-KEY-FOR-MANDRILL'), 
         data={'from': '[email protected]', 
          'to': '[email protected]', 
          'subject': 'Email from scraper', 
          'html': html}) 
関連する問題