Tech or Treat! Write an article about your scariest tech disaster to win gadgets!Learn more

x
?
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
Medium Priority
?
1,253 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

What’s Wrong with Your Cloud Strategy ?

Even as many CIOs are embracing a cloud-first strategy, the reality is that moving to the cloud is a lengthy process and the end-state is likely to be a blend of multiple clouds—public and private. Learn why multicloud solutions matter in this webinar by Nimble Storage.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
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
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

647 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