defsend_multiple_message(self):"""批量发送"""# 模板填充内容withopen(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.defsend_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!"})
附件
defsend_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>"})
图片
defsend_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>'})
带动态信息
defsend_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}}')})