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 = "mg.mynotsosupersecretdomain.com";
            // 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 <Jimmy.Neutron@gmail.com>"),
                        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 = "https://api.mailgun.net/v3/" + DOMAIN + "/messages"; var result = client.PostAsync(requestUri, content).Result; //TODO do something with the result... //like log it... or something dude. } } }

2 comments:

  1. Hey, Wow all the posts are very informative for the people who visit this site. Good work! We also have a Website. Please feel free to visit our site. Thank you for sharing.
    Be Your Own Boss! If you're looking for a change in your work prospects, then let's prepare for your career from here!!!
    Self Employment | Women Development | Information Technology | Engineering Courses

    ReplyDelete
  2. This is a very insightful breakdown of how automated, self-executing agreements are transforming modern supply chains and financial systems. The transition from legacy backend systems to blockchain-based workflows requires careful planning around authorization, security, and scalability. At Vegavid Technology, as a Custom Smart Contract Development Company in USA, we understand the importance of aligning contract logic with core business rules from the beginning. Integrating smart contracts with Machine Learning Development Company solutions, Image Processing Development Company capabilities, and an Agentic AI Development Company approach can further enhance automation and operational efficiency. These innovations also create opportunities to build intelligent customer experiences, including solutions that explain How to Build an AI Chatbot for Customer Support. Excellent read!

    ReplyDelete