Mailersend Email

The code below transmits your emails via the Mailersend (https://mailersend.com/) web service.

To use this method, you must have…

  • Created a Mailersend account,
  • Confirmed your sending email address,
  • Added the options in the table below to your Other Options in Settings, and
  • Installed the mailersend package in Python on the ReportList server.

Options

OptionDescription
msendfromThe sender email address
msendnameA human-readable name for the sender
msendtokenAn API token
import os
import json
import traceback
import base64
 
pth = os.path.dirname(__file__) + "/content.json"
f = open(pth,'r')
content = f.read()
f.close()
 
content = json.loads(content)
messages = content['messages']
fromaddr = content["options"]["msendfrom"]
fromname = content["options"]["msendfromname"]
token = content["options"]["msendtoken"]
 
from mailersend import emails
 
try:    
 
    for msg in messages:
        try:            
            mailer = emails.NewEmail(token)
 
            mail = {}
 
            frominfo = {
                "name": "From Name",
                "email": fromaddr
            }
 
            toinfo = []
            toinfo.append({
                "name": msg['to']['name'],
                "email": msg['to']['name']
            })
 
            attachments = []
 
            indx = 0
            for rep in msg['attachments']:
                #print(str(rep))
                attachment = open(rep['path'], 'rb')
                att_read = attachment.read()
                att_base64 = base64.b64encode(bytes(att_read))
                attachment.close()
                attachments.append({
                    "id": "report-" + str(indx),
                    "filename": rep['name'],
                    "content": f"{att_base64.decode('ascii')}",
                    "disposition": "attachment"
                })
                indx += 1
 
 
            mailer.set_mail_from(frominfo,mail)
            mailer.set_mail_to(toinfo,mail)
            mailer.set_subject(msg['title'],mail)
            mailer.set_plaintext_content(msg['content'],mail)
            mailer.set_html_content(msg['richcontent'],mail)
            mailer.set_attachments(attachments,mail)
            mailer.send(mail)
 
            print("-----")
            print("SUCCESS")
        except:
            print("-----")
            print("FAILURE")
            traceback.print_exc()
            pass
 
except Exception as ex:
    print("-----")
    print("FAILURE")