giovedì 8 agosto 2013

C# - Sending Html Mail With Image(s)

Sometimes could be usefull sending html mail with image as a web page; we can use it for different purposes, for example news letters or  advertisements.
The Following Code shows how is possible to do it in C#.

...


using System.Net.Mail;
using System.Net.Mime;

...




string body = "<html> " +
              "     <head> " +
              "          <title>You HTML Mail With Image</title> " +
              "     </head> " +
              "     <body> " +
              "     <img src='cid:YourImage' /> " +
              "     </body> " +
              "</html>";


            SendMail("from@domain.com", "FromDescription", "to@domain.com", "ToDescription", "MailObject", body, "smtp.yourserver.com", "User", "Password");





private void SendMail(string from, string FromDescription, string to, string toDescription, string MailObject, string body, string SmtpServer, string user, string password)
        {
            MailMessage mailMessageWithEmbeddedPicture = new MailMessage();
            mailMessageWithEmbeddedPicture.IsBodyHtml = true;
            mailMessageWithEmbeddedPicture.From = new MailAddress(from, FromDescription);
            mailMessageWithEmbeddedPicture.To.Add(new MailAddress(to, toDescription));

            mailMessageWithEmbeddedPicture.Subject = MailObject;
            mailMessageWithEmbeddedPicture.Body = body;


            AlternateView altViewHtml = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);

            LinkedResource embeddedPicture = new LinkedResource("YourImage.jpg", MediaTypeNames.Image.Jpeg);
            embeddedPicture.ContentId = "YourImage";

            altViewHtml.LinkedResources.Add(embeddedPicture);

            string warningMessage = "Use an E-mail Client that support HTML message!";

            ContentType contType = new ContentType("text/plain");
            AlternateView altViewText = AlternateView.CreateAlternateViewFromString(warningMessage, contType);

            mailMessageWithEmbeddedPicture.AlternateViews.Add(altViewHtml);


            SmtpClient smtpClient = new SmtpClient(SmtpServer);
            smtpClient.Credentials = new System.Net.NetworkCredential(user, password);

            smtpClient.Send(mailMessageWithEmbeddedPicture);
        }

  
My Two Cents ...

Nessun commento:

Posta un commento