SendGrid: Inviare Mail da Azure (Cloud Application)

L’amicizia tra me e SendGrid è nata la scorsa estate quando per un cliente dovevo effettuare una Cloud application (e relative Azure Function) con generazione ed invio di email al determinarsi di eventi specifici.

SendGrid: costi ed abbonoamenti

SendGrid è un servizio a pagamento, ma esiste anche la versione free. Il costo è determinato dal numero di mail inviate. Per i dettagli su costi e volumi di mail giornaliere mensili, si consiglio di vedere la sezione " Pricing and Plans” del sito ufficiale. Nel mio caso essendo (abbondantemente) sotto il traffico del piano free (40,000 emails for your first 30 days, then send 100/day, forever) ho un notevole risparmio e la garanzia di un servizio ottimo.

Perché ho parlato di costi in primo? La risposta è semplice. Per potere usare il servizio di SendGrid è necessaria una propria ApiKey e questa verrà fornita una volta sottoscritto il proprio piano.

SendGrid: Come attivarlo

Per attivare il servizio di SendGrid è sufficiente andare all’interno del portale Azure (= Azure Portal) ed aggiungere una nuova componente tramite i seguenti passi:

  1. Create a Resource

  2. Nella casella di ricerca scrivere “SendGrid Email Delivery

  3. Selezionare il componente

  4. Scegliere il  piano di abbonamento desiderato dalla lista “select a software plan”

  5. A questo punto verranno chiesti i dettagli per la creazione del componente SendGrid come Name, Password, Subscription, Promotion Code ed infine la scelta (=conferma) del piano di abbonamento.

A questo punto non resta che aspettare la creazione del componente e poi siete pronti per utilizzarlo

SendGrid: C# Helper

Per evitare di scrivere ogni volta la classe per inviare le mail con SendGrid ho scritto un helper nel mio componente in modo da averlo sempre pronto all’uso. Come vedrete in poche righe di codice è possibile sfruttare a pieno tutte le potenzialità. SendGrid - C# HowTo (Source Code)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110

using SendGrid;
using SendGrid.Helpers.Mail;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace DevAndreaCarrattaIT.Common
{
    public class SendGridMail
    {

        private string _apiKey = Guid.NewGuid().ToString();
        private bool _hasAttachment = false;

        public SendGridMail(string apiKey)
        {
            this._apiKey = apiKey;
        }

        public List<string> To { get; set; }
        public List<string> Cc { get; set; }
        public List<string> Bcc { get; set; }

        public void RemoveAttachment()
        {
            if (_hasAttachment)
            {
                _attachmentToSend = string.Empty;
                _attachmentToSendName = string.Empty;
                _attachmentToSendType = string.Empty;
                _hasAttachment = false;
            }
        }

        public void AddAttachment(string contentBase64, string fileName, string fileType)
        {
            _attachmentToSend = contentBase64;
            _attachmentToSendName = fileName;
            _attachmentToSendType = fileType;

            _hasAttachment = true;
        }
        private string _attachmentToSend { get; set; }
        private string _attachmentToSendName { get; set; }
        private string _attachmentToSendType { get; set; }

        public async Task<bool> Send(string fromMail, string fromName, string title, string text)
        {
            var client = new SendGridClient(this._apiKey);
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(fromMail, fromName));

            var recipients = new List<EmailAddress>();

            if (this.To != null && this.To.Count > 0)
            {
                recipients.Clear();
                foreach (string item in this.To)
                {
                    recipients.Add(new EmailAddress(item));
                }
                msg.AddTos(recipients);
            }

            if (this.Cc != null && this.Cc.Count > 0)
            {
                recipients.Clear();
                foreach (string item in this.Cc)
                {
                    recipients.Add(new EmailAddress(item));
                }
                msg.AddCcs(recipients);
            }

            if (this.Bcc != null && this.Bcc.Count > 0)
            {
                recipients.Clear();
                foreach (string item in this.Bcc)
                {
                    recipients.Add(new EmailAddress(item));
                }
                msg.AddBccs(recipients);
            }

            msg.SetSubject(title);

            if (this._hasAttachment)
            {
                Attachment attachment = new Attachment();
                attachment.Content = _attachmentToSend;
                attachment.Type = _attachmentToSendType;
                attachment.Filename = _attachmentToSendName;
                attachment.Disposition = "attachment";
                msg.AddAttachment(attachment);
            }

            StringBuilder builder = new StringBuilder();
            builder.AppendLine(text);
         
            msg.AddContent(MimeType.Html, $"<p>{builder.ToString()}</p>");
            var response = await client.SendEmailAsync(msg);

            return (response.StatusCode == System.Net.HttpStatusCode.OK);

        }
    }
}

SendGrid: Installazione Nuget

Per utilizzare il tutto è necessario aggiungere il pacchetto SendGrid attraverso nuget. Per farlo è sufficiente lanciare dal package manager il seguente comando:

Install-Package Sendgrid -Version 9.10.0

Per restare aggiornati con la versione più recente vi invito a vedere la pagina " NuGet Gallery | Sendgrid” con tutte le versioni del prodotto.