Doug Null
Doug Null

Reputation: 8327

how to send an email using SendGrid V3 to multiple recipients, in a .NET app

It sends to one ok. But not to 2 or more. I've tried separating addresses by , and ; and space in the to_addr string, but failed.

What format does class EmailAddress expect for multiple addresses?

    public async sub  send_message( msg_subject, msg_body, from_addr_text, to_addr_text, optional commands = "")
       dim apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY")
       dim client as  new SendGridClient( apiKey, , , "v3",  )

       dim from = new EmailAddress( from_addr_text, "INSTRUMENT")
       dim subject = msg_subject
       if subject = ""
        subject = " "       ' won't send if empty
       End If
       dim to_addr = new EmailAddress( to_addr_text, "INSTRUMENT")
       dim plainTextContent = msg_body
       dim htmlContent = "<strong>" & msg_body & "</strong>"
       dim msg = MailHelper.CreateSingleEmail(from, to_addr, subject, plainTextContent, htmlContent)
       dim response = await client.SendEmailAsync(msg)
       if instr( commands, "SKIP POPUPS")           ' TEST TEXT MSG !!!
            exit sub
       End If
       popup_information( "MESSAGE SENDING", "Sent..." & vbcrlf & vbcrlf & "SUBJECT:  " & vbcrlf &  subject  &   vbcrlf & vbcrlf & "BODY:  " & vbcrlf &  msg_body )
end sub

Upvotes: 1

Views: 3737

Answers (2)

DMendoza
DMendoza

Reputation: 453

The stack overflow answer here shows how to implement SendGrid using dependency injection into a Net 6 Web API application using controllers.

The scenario of sending an email to multiple recipients is covered in the referenced example code here: https://github.com/Davidmendoza1987/dotnet-sendgrid-examples

Upvotes: 0

Niladri
Niladri

Reputation: 5962

Not sure which SDK version are you using , but if you follow the Sendgrid V3 api SDK for C# , you should find a method like below in the MailHelper class

public static SendGridMessage CreateSingleEmailToMultipleRecipients(EmailAddress from, List<EmailAddress> tos, string subject,string plainTextContent,string htmlContent)

which accepts a List<EmailAddress> to send email to multiple recipients. So instead of using the below line in your code

dim msg = MailHelper.CreateSingleEmail(from, to_addr, subject, plainTextContent, htmlContent)

you should use the below code

   var to_addr = new List<EmailAddress>();
   to_addr.Add(new EmailAddress( to_addr_text, "INSTRUMENT"));
   to_addr.Add(new EmailAddress( "[email protected]", "secondperson")); // you can add multiple email in this list 

and then you can use to_addr in the code below

dim msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to_addr, subject, plainTextContent, htmlContent)

Pardon me for the example in C# but the same should be applicable for your VB.NET code

Upvotes: 1

Related Questions