Created
May 2, 2014 10:34
-
-
Save thinrhino/a873d23bee8ef71311fd to your computer and use it in GitHub Desktop.
Send mails using Mandrill API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from mandrill import Mandrill | |
import base64 | |
mail_client = Mandrill('<api_key>') | |
frm_email = '[email protected]' | |
frm_name = 'Given Name' | |
# Sending image as attachment | |
img_attachment = base64.b64encode(open('~/sample_image.jpg', 'rb').read()) | |
# Reading the raw text message to send in each email | |
raw_message = open('./data/text_msg.txt', 'r').read() | |
fields = ('c_name', 'f_name', 'l_name', 'email', 'p_msg') | |
# A CSV file containing: | |
# greeting name, first name, last name, email id, personal message | |
# John, John, Doe, [email protected], How are you doing? | |
# The personal message currently gets appeneded to the bottom of the | |
# email as a 'PS:' | |
recepients = open('./data/email.csv', 'r') | |
while True: | |
l = recepients.readline().strip().split(',') | |
if len(l) == 1: | |
break | |
p = dict(zip(fields, l)) | |
if p['p_msg']: | |
txt_msg = "Hello %s,\n\n%s\n\nPS: %s" % (p['c_name'], raw_message, p['p_msg']) | |
else: | |
txt_msg = "Hello %s,\n\n%s\n" % (p['c_name'], raw_message) | |
result = mail_client.messages.send(message=create_msg(p, txt_msg), async=False) | |
print result | |
def create_msg(p, msg): | |
message = { | |
'auto_html' : True, | |
'from_email' : frm_email, | |
'from_name' : frm_name, | |
'headers' : { | |
'Reply-To' : frm_email, | |
}, | |
'text' : msg, | |
'to' : [{'email' : p['email'], | |
'name' : '%s %s' % (p['f_name'], p['l_name']), | |
'type' : 'to'}], | |
'track_clicks' : True, | |
'track_opens' : True, | |
'images' : [{ | |
'content':img_attachment, | |
'name' : 'image.jpg', | |
'type' : 'image/jpg'}], | |
'subject' : '', | |
'signing_domain' : 'domainname' | |
} | |
return message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 49 could be changed to:
'name' : '{0.f_name} {0.l_name}'.format(p),