Search code examples
c#asp.netasp.net-mvcmailjet

How to add content to newsletter in Mailjet API v3 using ASP .NET MVC 5


I am able to send empty newsletters. But I dont know how to add content to them. Example given by the Mailjet (http://dev.mailjet.com/guides/newsletter-guide/) does not help much. I get 500 Internal Server Error most of the time.

Calling method:

NewsLetterHtmlAdd newsLetterAdd = new NewsLetterHtmlAdd
        {
            ID = idNewsletter,
            Data = string.Format("<!DOCTYPE html" +
                                 "<html>" +
                                 "<head>" +
                                 "<meta content='text/html; charset=utf-8' http-equiv='Content-Type' />" +
                                 "<title>Subject</title>" +
                                 "</head>" +
                                 "<body>" +
                                 "<p style='text-align: center'>Sender <a href='mailto:[[EMAIL_TO]]'>[[EMAIL_TO]]</a>, " + "<a href='[[UNSUB_LINK_EN]]'>Unsubscribe here</a>.</p>"
                                 +
                                 "</body>" +
                                 "</html>")
        };
client.NewsLetterHtmlAdd(newsLetterAdd);

Method:

    public void NewsLetterHtmlAdd(NewsLetterHtmlAdd newsLetterHtmlAdd)
    {
string url = "https://api.mailjet.com/v3/DATA/NewsLetter/"
                     + newsLetterHtmlAdd.ID + "/HTML/text/html/";



        byte[] byteArray = new byte[newsLetterHtmlAdd.Data.Length*sizeof (char)];
        Buffer.BlockCopy(newsLetterHtmlAdd.Data.ToCharArray(), 0, byteArray, 0, byteArray.Length);
        WebRequest request = WebRequest.Create(url);
        request.Credentials = new NetworkCredential(_apiKey, _secretKey);
        request.Method = "POST";
        request.ContentLength = byteArray.Length;
        request.ContentType = "text/html";
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        WebResponse response = request.GetResponse();
    }

ViewModel:

using System.Runtime.Serialization;

namespace MailJet.Newsletter
{  [DataContract] 
public class NewsLetterHtmlAdd
{

[DataMember(Name = "id")]
public long ID { get; set; }


[DataMember(Name = "data")]
public string Data { get; set; }
}
}

Solution

  • this is the method that works for me. I use ServiceStack.

        public void NewsLetterHtmlAdd(NewsLetterHtmlAdd newsLetterHtmlAdd)
        {
            string url = "https://api.mailjet.com/v3/DATA/NewsLetter/" + newsLetterHtmlAdd.ID + "/HTML/text/html/";
    
            url.PostToUrl(newsLetterHtmlAdd.Data, "text/html; charset=utf-8",
                  request =>
                  {
                      request.Credentials = new NetworkCredential(_apiKey, _secretKey);
                      request.ContentType = "text/html; charset=utf-8";
                  });
    
        }