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,107 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
 
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

760 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now