Thursday, December 29, 2016

Sending emails with .NET Core v1.1 and mailgun with attachements

I simply wanted to send some emails programmatically using .NET Core v1.1 with attachments.
Perhaps I should have chosen a different route, however I had already signed up for a 
mailgun account as it seemed like that would be the quickest and easiest way to do it.  
Perhaps it was... but it certainly wasn't very quick, and wasn't exactly easy; 
atleast not until I figured it out.  Now it seems super quick, and super easy.  

I hope this helps someone save some time.  Peace.

public static void SendEmailWithAttachement
(string emailTo, string emailSubject, string emailText, byte[] attachmentByteArray, string attachmentFileName)
            // the domain name you have verified in your Mailgun account
            const string DOMAIN = "";
            // your API Key used to send mail through the Mailgun API
            const string API_KEY = "key-mysupersecretkey";

            using (var client = new HttpClient())
                client.DefaultRequestHeaders.Authorization = 
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes("api" + ":" + API_KEY)));

                using (var content = new MultipartFormDataContent())
                    var values = new[]
                        new KeyValuePair<string, string>("from", "Jimmy Neutron <>"),
                        new KeyValuePair<string, string>("to", emailTo),
                        new KeyValuePair<string, string>("subject", emailSubject),
                        new KeyValuePair<string, string>("text", emailText)

                    foreach (var keyValuePair in values)
                        content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
                    var fileContent = new ByteArrayContent(attachmentByteArray);//(System.IO.File.ReadAllBytes(fileName));
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        Name = "attachment",
                        DispositionType = "form-data",
                        CreationDate = DateTime.Now,
                        Size = attachmentByteArray.Length,
                        FileName = attachmentFileName,
content.Add(fileContent); var requestUri = "" + DOMAIN + "/messages"; var result = client.PostAsync(requestUri, content).Result; //TODO do something with the result... //like log it... or something dude. } } }

No comments:

Post a Comment