emailgun一个请求批量发送邮件

个人封装的一个批量发送动态内容的方法

 def send_multiple_message(self):
     """批量发送"""
     # 模板填充内容
     with open(self.template.template, encoding='utf-8') as f:
         content = f.read().replace('\n', '').replace('\r', '').replace('\r\n', '')
     year = datetime.now().year
     subject = f'{self.app} {self.template.subject}'
     emails = list()
     variables = {}
     for i in self.emails:
         day = (datetime.strptime(i['expirationtime'], '%Y-%m-%d') - datetime.now()).days + 1
         con = {
             'app': self.app,
             'subject': subject,
             'name': i['name'],
             'expirationtime': i['expirationtime'],
             'day': day,
             'year': year
         }
         variables[i['email']] = con
         emails.append(i['email'])
     try:
         r = requests.post(f'{self.template.base_url}/messages',
                           auth=("api", self.template.api_key),
                           data={'from': f'{self.template.verifier_name} <{self.template.verifier}>',
                                 "to": emails,
                                 "subject": subject,
                                 "html": content,
                                 "recipient-variables": json.dumps(variables)
                                 }
                           )
         r.raise_for_status()
         root = r.json()
         id = root['id']
         logger.info(f'Sent "{subject}" email#{id} to {emails}')
     except:
         logger.exception(f'Send "{subject}" email failed to {emails}.')
     logger.info(f'{len(self.emails)} emails with the subject of {subject} were successfully sent')

官方文档

	
# Try running this locally.
def send_simple_message():
    return requests.post(
        "https://api.mailgun.net/v3/samples.mailgun.org/messages",
        auth=("api", "key-3ax6xnjp29jd6fds4gc373sgvjxteol0"),
        data={"from": "Excited User <excited@samples.mailgun.org>",
              "to": ["devs@mailgun.net"],
              "subject": "Hello",
              "text": "Testing some Mailgun awesomeness!"})
附件
def send_complex_message():
    return requests.post(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
        auth=("api", "YOUR_API_KEY"),
        files=[("attachment", ("test.jpg", open("files/test.jpg","rb").read())),
               ("attachment", ("test.txt", open("files/test.txt","rb").read()))],
        data={"from": "Excited User <YOU@YOUR_DOMAIN_NAME>",
              "to": "foo@example.com",
              "cc": "baz@example.com",
              "bcc": "bar@example.com",
              "subject": "Hello",
              "text": "Testing some Mailgun awesomness!",
              "html": "<html>HTML version of the body</html>"})
图片
def send_inline_image():
    return requests.post(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
        auth=("api", "YOUR_API_KEY"),
        files=[("inline", open("files/test.jpg"))],
        data={"from": "Excited User <YOU@YOUR_DOMAIN_NAME>",
              "to": "bar@example.com",
              "subject": "Hello",
              "text": "Testing some Mailgun awesomness!",
              "html": '<html>Inline image here: <img src="cid:test.jpg"></html>'})
带动态信息
def send_template_message():
    return requests.post(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
        auth=("api", "YOUR_API_KEY"),
        data={"from": "Excited User <YOU@YOUR_DOMAIN_NAME>",
              "to": ["alice@example.com, bob@example.com"],
              "subject": "Hey, %recipient.first%",
              "text": "If you wish to unsubscribe, click http://mailgun/unsubscribe/%recipient.id%'",
              "recipient-variables": ('{"bob@example.com": {"first":"Bob", "id":1}, '
                                      '"alice@example.com": {"first":"Alice", "id": 2}}')})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值