Skip to content

Instantly share code, notes, and snippets.

@thinrhino
Created May 2, 2014 10:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thinrhino/a873d23bee8ef71311fd to your computer and use it in GitHub Desktop.
Save thinrhino/a873d23bee8ef71311fd to your computer and use it in GitHub Desktop.
Send mails using Mandrill API
from mandrill import Mandrill
import base64
mail_client = Mandrill('<api_key>')
frm_email = 'email@email.com'
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, john.doe@gmail.com, 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
@shantanoo
Copy link

Line 49 could be changed to:

'name' : '{0.f_name} {0.l_name}'.format(p),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment