Search code examples
c#email-clientrazorengine

How can i send email from c# that contain graphics as dygraph js does?


I need to send email report from c# code. This email contain graphic like the image. is there any way to make that in c#? dygraph graphic must be included in the email


Solution

  • You can use the MailMessage class to construct the email, and the SmtpClient class to send the message. You'll need to set up the SmtpClient appropriately*.

    In order to embed an image, you need to set the email to be HTML, and include an alternate view with the embedded image:

    var mail = new MailMessage();
    mail.IsBodyHtml = true;
    
    var inline = new LinkedResource(@"C:\path\to\your\image.png");
    inline.ContentId = Guid.NewGuid().ToString();
    var htmlBody = @"<img src='cid:" + inline.ContentId + @"'/>"; // Include whatever other content in the html body here.
    var alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
    alternateView.LinkedResources.Add(inline);
    
    mail.AlternateViews.Add(alternateView);
    

    Then set the to/from/subject fields and use the SmtpClient.Send Method (or SendAsync) to send the email.

    *From the MSDN docs:

    To construct and send an e-mail message by using SmtpClient, you must specify the following information:

    • The SMTP host server that you use to send e-mail. See the Host and Port properties.

    • Credentials for authentication, if required by the SMTP server. See the Credentials property.

    • The e-mail address of the sender. See the Send and SendAsync methods that take a from parameter. Also see the MailMessage.From property.

    • The e-mail address or addresses of the recipients. See the Send and SendAsync methods that take a recipient parameter. Also see the MailMessage.To property.

    • The message content. See the Send and SendAsync methods that take a body parameter. Also see the MailMessage.Body property.