How to use razor engine for email templating with image src

后端 未结 1 1525
梦如初夏
梦如初夏 2020-12-06 12:44

I\'ve found this link on how to using Razor Engine for email templates in asp.net and it worked great. But I\'ve tried to have a logo in the email template with an image.

相关标签:
1条回答
  • 2020-12-06 13:38

    To see image everywhere you can use these options:

    Absolute Url

    You can simply use full absolute path of image for example "http://example.com/images/logo.png"

    IMO It is the most simple option and recommended for your problem.

    Attachment

    As mentioned by Mason in comments You can attach image to mail and then put image tag and useContentId of attachment:

    //(Thanks to Mason for comment and Thanks to  Bartosz Kosarzyck for sample code)
    string subject = "Subject";
    string body = @"<img src=""$CONTENTID$""/> <br/> Some Content";
    
    MailMessage mail = new MailMessage();
    mail.From = new MailAddress("from@example.com");
    mail.To.Add(new MailAddress("to@example.com"));
    mail.Subject = subject;
    mail.Body = body;
    mail.Priority = MailPriority.Normal;
    
    string contentID = Guid.NewGuid().ToString().Replace("-", "");
    body = body.Replace("$CONTENTID$", "cid:" + contentID);
    
    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
    //path of image or stream
    LinkedResource imagelink = new LinkedResource(@"C:\Users\R.Aghaei\Desktop\outlook.png", "image/png");
    imagelink.ContentId = contentID;
    imagelink.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
    htmlView.LinkedResources.Add(imagelink);
    mail.AlternateViews.Add(htmlView);
    
    SmtpClient client = new SmtpClient();
    client.Host = "mail.example.com";
    client.Credentials = new NetworkCredential("from@example.com", "password");
    client.Send(mail);
    

    Data Uri

    you can use data uri (data:image/png;base64,....).

    Not Recommended because of weak support in most of mail clients, I tested it with Outlook.com(web) and OutlookWebAccess(web) and Office Outlook(Windows) and Outlook(windows 8.1) and unfortunately it worked only on OutlookWebAccess(web).

    0 讨论(0)
提交回复
热议问题