Search code examples
c#azureazure-functionssendgridsendgrid-api-v3

sendgrid send email to multiple recipients in Azure function failed


(For the complete version of this question, please refer to https://social.msdn.microsoft.com/Forums/en-US/20bb5b37-82af-4cf3-8a59-04e5f19572bc/send-email-to-multiple-recipients-using-sendgrid-failure?forum=AzureFunctions)

Sending to single recipient was successful. But found no way to send to multiple recipients or CC/BCC in Azure function.

Tried several formats including

{ "to": [{ "email": ["[email protected]", "[email protected]" ] }] }

It seemed to be the limit from azure function. But not sure where goes wrong yet. Please refer to the "bindings" below,

{

"bindings": [

{

"name": "telemetryEvent",

"type": "serviceBusTrigger", 

"direction": "in",

"queueName": "threshold-email-queue",

"connection": "RootManageSharedAccessKey_SERVICEBUS",

"accessRights": "Manage"

},

{

"type": "sendGrid",

"name": "$return",

"apiKey": "SendGridKey",

"direction": "out",

"from": "[email protected]",

"to": [{
"email": ["[email protected]", "[email protected]" ]
}]

}

],
"disabled": false

}

Solution

  • Thanks to Tamás Huj, the function can do the job now. So I post the solution in detail for others reference.

    {
    "bindings": [
    
    {
    
    "name": "telemetryEvent",
    
    "type": "serviceBusTrigger", 
    
    "direction": "in",
    
    "queueName": "threshold-email-queue",
    
    "connection": "RootManageSharedAccessKey_SERVICEBUS",
    
    "accessRights": "Manage"
    
    },
    
    {
    
    "type": "sendGrid",
    
    "name": "$return",
    
    "apiKey": "SendGridKey",
    
    "direction": "out",
    
    "from": "[email protected]"
    
    }
    
    ],
    "disabled": false
    
    }
    

    Then write the run.csx as:

    #r "SendGrid"
    #r "Newtonsoft.Json"
    
    using System;
    using SendGrid.Helpers.Mail;
    using System.Threading.Tasks;
    using Microsoft.Azure.WebJobs.Host;
    using Newtonsoft.Json;
    
    public static Mail Run(string telemetryEvent, TraceWriter log)
    {
        var telemetry = JsonConvert.DeserializeObject<Telemetry>(telemetryEvent);
    
    Mail message = new Mail()
    {
        Subject = "Write your own subject"
    };
    
    var personalization = new Personalization();
    personalization.AddBcc(new Email("[email protected]"));  
    personalization.AddTo(new Email("[email protected]")); 
    //add more Bcc,cc and to here as needed
    
    Content content = new Content
    {
        Type = "text/plain",
        Value = $"The temperature value is{temperature.Temperature}."
    };
    
    message.AddContent(content); 
    message.AddPersonalization(personalization); 
    
        return message;
    }
    
    
    public class Telemetry 
    {
        public float Temperature { get; set; }
    }