Azure Communication Services Delivery

The code below transmits your reports via email using Azure Communication Services, bypassing common issues with SMTP servers.

To use this method, you must have…

import os
import json
import traceback
import base64
 
def GetFileContent(fname):
    content = None
    with open(fname,'rb') as img:
        content = base64.b64encode(img.read())
 
    return content
 
 
pth = os.path.dirname(__file__) + "/content.json"
f = open(pth,'r')
content = f.read()
f.close()
 
content = json.loads(content)
messages = content['messages']
comkey = content["options"]["azurekey"]
fromaddr = content["options"]["azureemail"]
 
from azure.communication.email import EmailClient
 
try:
    connection_string = "endpoint=https://cservices.australia.communication.azure.com/;accesskey=" + comkey
    client = EmailClient.from_connection_string(connection_string)
 
    for msg in messages:
        try:
            toaddress = msg['to']
            recip = []            
            recip.append({"address": toaddress['name']})
 
            message = {
                "senderAddress": str(fromaddr),
                "recipients":  {
                    "to": recip,
                },
                "content": {
                    "subject": msg['title'],
                    "plainText": msg['content'],
                    "html": msg['richcontent']
                },
                "attachments": []
            }
 
            for at in msg['attachments']:
                nitem = {}
                ct = GetFileContent(at['path'])
                if ct is not None:
                    nitem['name'] = at['name']
                    nitem['contentType'] = at['contenttype']
                    nitem['contentInBase64'] = ct.decode()
                    message['attachments'].append(nitem)
 
            #print(str(message))
 
            poller = client.begin_send(message)
            result = poller.result()
 
            print("-----")
            print("SUCCESS")
        except:
            print("-----")
            print("FAILURE")
            traceback.print_exc()
            pass
 
except Exception as ex:
    print("-----")
    print("FAILURE")