C# Send email with embed image - JackHu88/Comm GitHub Wiki

Send email with embed image

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace EmailTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string subject = "Test";

            string[] toAddress = new string[] { "[email protected]", "[email protected]"};

            string body = "<img src=cid:myImageID>";

            sendHtmlEmail("[email protected]",toAddress , subject, body);

        }

        static void sendHtmlEmail(string from_Email, string[] toAddress, string subject, string body)
        {
            MailMessage mail = new MailMessage();
            mail.IsBodyHtml = true;

            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");

            String path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + @"\Images\1.jpg";
            LinkedResource theEmailImage = new LinkedResource(path);
            theEmailImage.ContentId = "myImageID";

            htmlView.LinkedResources.Add(theEmailImage);
            mail.AlternateViews.Add(htmlView);
            mail.From = new MailAddress(from_Email);
            foreach (string to in toAddress)
            {
                mail.To.Add(to);
            }          
            mail.Subject = subject;
            mail.Body = body;


            /*String userName = "[email protected]";
            String password = "pwd123";
            MailMessage msg = new MailMessage();
            msg.To.Add(new MailAddress("[email protected]"));
            msg.From = new MailAddress("test");
            msg.Subject = "Test Office 365 Account";
            msg.Body = "Testing email using Office 365 account.";
            msg.IsBodyHtml = true;
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.sp2013.com";
            client.Credentials = new System.Net.NetworkCredential(userName, password);
            client.Port = 25;
            client.Send(msg);*/


            SmtpClient client = new SmtpClient("smtp.sp2013.com");
            client.UseDefaultCredentials = true;
            try
            {
                client.Send(mail);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught: {0}", ex.ToString());
            }

        }

    }
}