Solved

c# auto embed images into html email, i have full code, all looks fine but images arent embdeded...

Posted on 2011-03-03
9
1,153 Views
Last Modified: 2012-05-11
hi all my code below has no errors i recieve the email btu the images arent embdeded, i can see they have their cids in there and the output of editor1.text is

which all looks fine, btu see screen of email...

Key - /uploads/12.jpg<br />
Value - cid:image1<br />
ImageURL - E:\net folder\uploads\12.jpg<br />
Imagename - image1<br />
Key - /uploads/13.jpg<br />
Value - cid:image2<br />
ImageURL - E:\net folder\uploads\13.jpg<br />
Imagename - image2
protected void SendEmail(object sender, EventArgs e)
    {
        try
        {
            
            MailMessage mail = new MailMessage();

            mail.From = new MailAddress("mailout@****.***");
            mail.To.Add("alex@***.******");
            mail.Subject = "Test Mail";
            mail.IsBodyHtml = true;

            string htmlBody;
            string plainBody;
            //htmlBody = Editor1.XHTML;
            plainBody = Editor1.PlainText;

            AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, null, "text/plain");
            AlternateView htmlView = AlternateView.CreateAlternateViewFromString("", null, "text/html"); ;

            Dictionary<string, string> imgSources = new Dictionary<string, string>();
            // Start with cid:image1 and go up 1 for each <img> tag
            int firstNumber = 1;
            // What to replace the src with - the {0} part represents where the number should go - so you could use image{0}.jpg to get image1.jpg, image2.jpg, image3.jpg, etc
            string replacement = "cid:image{0}";
            // Run the SourceTextBox contents through the <img> tag replacer, and assign
            // the results to the DestinationTextBox
            htmlBody = Functions.ExtractImages(
                Editor1.XHTML, // The HTML source to have <img> tags replaced
                replacement, // What to replace the src with - the {0} part represents where the number should go - so you could use image{0}.jpg to get image1.jpg, image2.jpg, image3.jpg, etc
                firstNumber, // Start with cid:image1 and go up 1 for each <img> tag
                ref imgSources  // The list of strings that will contain the original sources
            );
            // Now, write the original images and what they were replaced with
            // to a temporary StringBuilder
            foreach (KeyValuePair<string, string> originalSource in imgSources)
            {
                Editor1.Text += "<br />Key - " + originalSource.Key;
                Editor1.Text += "<br />Value - " + originalSource.Value;

                string strImageUrl = System.Web.HttpContext.Current.Server.MapPath(originalSource.Key);

                Editor1.Text += "<br />ImageURL - " + strImageUrl;
                Editor1.Text += "<br />Imagename - " + originalSource.Value.ToString().Replace("cid:", "");

                LinkedResource image = new LinkedResource(strImageUrl);
                image.ContentId = originalSource.Value.ToString().Replace("cid:", "");
                htmlView.LinkedResources.Add(image);

                firstNumber++;
            }
            
            //mail.Body = htmlBody;
            htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");

            mail.AlternateViews.Add(htmlView);
            mail.AlternateViews.Add(plainView);

            SmtpClient SmtpServer = new SmtpClient("ex.***.***");
            SmtpServer.Port = 25;
            SmtpServer.UseDefaultCredentials = true;
            SmtpServer.Send(mail);

            OutPut2.Text = plainBody;

        }
        catch (Exception ex)
        {
            OutPut2.Text += "<br />" + Convert.ToString(ex);
        }
        EditorUpdatePanel.Update();

Open in new window

Capture.PNG
0
Comment
Question by:awilderbeast
  • 5
  • 4
9 Comments
 
LVL 9

Expert Comment

by:jkofte
ID: 35026535
you cannot see the images that are in your disk from an e-mail server.
the program you read the e-mail must have proper authorization and also it should be able to view the images from the address. For example I cannot view X.doc file in your C: disk.

if you upload the images to web and display them from there, you can see them.
0
 
LVL 9

Expert Comment

by:jkofte
ID: 35026549
for example try to display the image http://kadirselcuk.com/wp-content/uploads/2011/03/iis7.jpg which is on my website. you should be able to see it.
0
 
LVL 1

Author Comment

by:awilderbeast
ID: 35026595
its getting pulled from my we server

if i put the images in c:\ and then typed C:\doggy.jpg that works as the linked resource fine

i thought it was because net folder had a space in, so i removed and edited iis but is still doesnt work,

jsut to try then, how do i get the virtual path of the current website in c#?
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 9

Expert Comment

by:jkofte
ID: 35026715
if you wish to use absoulte link you should use: /folder/image.jpg

this way the image path will start from the root part of the website.

if you wish to relative pathing you should use folder/image.jpg

this way the image path will start from the folder that the web page is in.

also if you wish to go to one lower level in relative pathing use ../folder/image.jpg
0
 
LVL 1

Author Comment

by:awilderbeast
ID: 35026753
if i change

string strImageUrl = System.Web.HttpContext.Current.Server.MapPath(originalSource.Key);
LinkedResource image = new LinkedResource(strImageUrl);

which is LinkedResource image = new LinkedResource("e:\netfolder\uploads\12.jpg");

to
LinkedResource image = new LinkedResource(originalSource.Key);

which it then thinks is LinkedResource image = new LinkedResource("c:\uploads\12.jpg");
and give back the below error!

how can i use a virtual path as a linked resource?

System.IO.DirectoryNotFoundException: Could not find a part of the path 'c:\uploads\12.jpg'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.Net.Mail.AttachmentBase.SetContentFromFile(String fileName, String mediaType) at Documents.SendEmail(Object sender, EventArgs e) in e:\netfolder\documents\documents.aspx.cs:line 352

Open in new window

0
 
LVL 9

Expert Comment

by:jkofte
ID: 35026866
i can see in your screenshot that you are trying to display the images from outlook, so the images should be in a website open to the users that will receive this mail.

if you are asking me how to create a website under your own pc, you will need to install IIS for that.
if you have IIS, then place the folders under c:\inetpub\wwwroot folder (which is default root folder) and you will be able to reach them as http://localhost/doggy.jpg
0
 
LVL 1

Author Comment

by:awilderbeast
ID: 35026896
sorry i dont think your understanding me here

i have a local web server, with my website on, and im using c# to embed images on the fly that are inserted into a wysyig using cid:image

so my function goes through the wysiwyg content and then strips out the sources of the iamges and replaces them with cid's
which is fine, but the code (below) somethign seems to be not working its not adding the imagse to the htmlView

and its nothing to do with the file path, the code is serverside code so its run on the server (where the images are located)

its just not embeding them, are you following?
string strImageUrl = System.Web.HttpContext.Current.Server.MapPath(originalSource.Key);
                LinkedResource image = new LinkedResource(strImageUrl);
                image.ContentId = originalSource.Value.ToString().Replace("cid:", "");
                htmlView.LinkedResources.Add(image);

Open in new window

0
 
LVL 1

Accepted Solution

by:
awilderbeast earned 0 total points
ID: 35027065
ive fixed it!

the problem was i was addeding the images before the html view

the below now works with the alternatview before the loop, my images are now embeded
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
            // Now, write the original images and what they were replaced with
            // to a temporary StringBuilder
            foreach (KeyValuePair<string, string> originalSource in imgSources)
            {
                string strImageUrl = System.Web.HttpContext.Current.Server.MapPath(originalSource.Key);
                LinkedResource image = new LinkedResource(strImageUrl);
                image.ContentId = originalSource.Value.ToString().Replace("cid:", "");
                htmlView.LinkedResources.Add(image);
                              
                Editor1.Text += "<br />Key - " + originalSource.Key;
                Editor1.Text += "<br />Value - " + originalSource.Value;
                Editor1.Text += "<br />ImageURL - " + strImageUrl;
                Editor1.Text += "<br />Imagename - " + originalSource.Value.ToString().Replace("cid:", "");

                firstNumber++;
            }

Open in new window

0
 
LVL 1

Author Closing Comment

by:awilderbeast
ID: 35067808
figured it out myself
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question