How can I display images in mail content? - c#

I want send e-mail with some images in content. I think I must attached this images as attachments to e-mail, but my proble is how can I use attached images in mail content?
CODE WHICH SEND MAIL
WebMail.SmtpServer = "my.smtp.server";
WebMail.Send(
clientEmail,
subject,
"<html><head></head><body><img src='???' /></body></html>",
myEmail,
null,
new List<string> () { "path" },
true
);
What I must write as src ?
Any help would be appreciated.

Also good sample at http://blog.devexperience.net/en/12/Send_an_Email_in_CSharp_with_Inline_attachments.aspx
System.Net.Mail.Message Class :
Sample ;
var msg = new System.Net.Mail.Message();
msg.isHTML=true;
msg.Body ="<img src=\"cid:IMG1CONTENT\">";
Attachment mya = new Attachment("file-path-here");
mya.ContentId="IMG1CONTENT";
msg.Attachments.Add(mya);
You can find more details # http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx

To display the images in email content, one solution is to have an absolute URL. Upload the images to your server and use the abosoluter url as the src attribute value
<img src='http://www.yourdomain.com/youfolder/image.jpg' alt='your image desc'/>
But some email clients will disable external images. So user may need to enable "show images" when propmpted so.

Related

How to attach multi images in email body in windows application?

I am working on windows application for email sending.
For text formatting i used tinymce editor for email body.
Used tinymce insert image functionality for adding image in email body but when email is sent to user. Images does not appear in user email body.
Then i tried to add base64 image manually as below:
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOYAAABLCAYAAABk6PuLAAAACXBIWXMAASdHAAEnRwEEDs /'>
Which is failed to load images.
Can we use linked resources and alternate view in tiny mce?
How to load images in email body?
Tiny MCE is just an HTML editor and not a tool which can be used for creating alternate views for email.
Moreover, all email clients don't support inline images (with data URL).
Alternate view is the only way to ensure that all email clients will be able to show your content in the intended manner.
Create a dictionary of linked resources:
Dictionary<string, byte[]> linkedResources = new Dictionary<string, byte[]>();
linkedResources.Add("img1", byte[]);
Create a common method to send email:
public bool SendEmail(Dictionary<string, byte[]> linkedResources)
{
using (SmtpClient mailSender = new SmtpClient("SmtpHost", 22))
{
MailMessage emailMessage = new MailMessage()
{
Subject = "Subject",
SubjectEncoding = Encoding.ASCII,
IsBodyHtml = true,
Body = "Message",
BodyEncoding = Encoding.ASCII,
From = new MailAddress("Sender#domain.com")
};
emailMessage.BodyEncoding = Encoding.ASCII;
emailMessage.IsBodyHtml = true;
AlternateView av = AlternateView.CreateAlternateViewFromString(emailMessage.Body, null, MediaTypeNames.Text.Html);
foreach (var item in linkedResources)
{
MemoryStream streamBitmap = new MemoryStream(item.Value);
var linkedResource = new LinkedResource(streamBitmap, MediaTypeNames.Image.Jpeg);
linkedResource.ContentId = item.Key;
av.LinkedResources.Add(linkedResource);
}
emailMessage.AlternateViews.Add(av);
mailSender.Send(emailMessage);
return true;
}
}
The real question you need to answer is "what is the best way to insert an image in an email". This is a very broad topic that has been answered many times - a little research should lead you to the most common approaches and their pros/cons:
https://sendgrid.com/blog/embedding-images-emails-facts/
https://www.campaignmonitor.com/blog/how-to/2008/08/embedding-images-in-email/
https://www.quora.com/Whats-the-best-practices-for-embedding-images-into-HTML-emails
there is no best solution for that, you can embed the images or attach them as files or just send them as links.
it depends on your requirements. it actually making image tags and link them to my server to get more analytics like the user had opened the email by loading the image throw a handler and the handler receive logs when the user opened the email and I can know how many users opened that email and so on.
Send grid is great for sending emails and getting analytics out of them because it tracks almost everything related to your email, and you should use Send grid to avoid Spam filters
In my experience the only way to solve this is to store that image on the server where it's publicly accessible and then point the img tag src attribute to that url. You have to understand that the HTML that's used in email is severely restricted to regular HTML.

C# WPF how to send mail with attachment

In my WPFapplication I need to be able to open the default email to send an email with attachment previously scanned.
For the scanner i used WIA and I save the scanned image in jpeg.
For email i has tried the MAILTO as follows
string mail1 = "abc#hotmail.com";
string mail2 = "def#yahoo.it";
string attach = #"C:\bla\bla\bla\file.xlsx";
Process.Start(string.Format("mailto:{0}?subject={1}&body={2}&CC={3}&attachment:{4}"
, mail1, subject, body, mail2,attach));
every thing works unless ATTACHMENT when Process.start opens the default email.
you know something better than mailto? or something that gives the ability to attach files to email?
You can upload that file to a server, get a URL and include it into mailto body as a link.

Cannot seem to add a custom text alternative view to my multipart email

I am writing a system to send out bulk emails to clients and for each site we store an HTML and Text version of the email so that if the users mail client doesn't support HTML the text view is still formatted correctly and as we want.
We don't want to just generate the plain text version from the HTML version as it adds in lots of menu links and other text which isn't formatted as we want.
This works fine in ASP classic with the Persits Email Component = http://www.aspemail.com/
as we add the HTML string as the Body and the text string as the AltBody.
However I am having trouble replicating this in C# .NET 4.5
I have followed as many examples as possible but my method that returns the MailMessage object which needs to pass the HTML looking for images/banners and then replace the URLS with ContentIDs and LinkedResources is somehow returning an email that looks great in HTML and Simple HTML View (in Thunderbird).
However whatever I do the plain text view seems to always be a version of the HTML that the object is trying to convert into text RATHER than the textual string we have pre-formatted and want to use.
If I debug the code I can see that the string is correct before I add it to the alternative view so I don't know what else I need to do.
In my method that parses the HTML, adds linked resources and returns a MailMessage object I have the following code:
<pre>
/* I pass in a custom SiteEmail object with 2 properties HTMLEmail and TextEmail that hold both versions of the email */
public MailMessage ParseEmailImages(SiteEmail siteEmail)
{
MailMessage email = new MailMessage();
// extract the HTML version as we need to parse it to swap URLs for ContentID/Resources and paths etc
string HTML = siteEmail.HTMLEmail;
// this is a generic list to hold all my picture resource objects that I find (swapping image URLs to paths and contentIDs)
List<LinkedResource> pictureResources = new List<LinkedResource>();
// code to find all the paths, create image resource objects and add them to my list - and modify the HTML to reference
// the new ContentIDs I swap the URLs for so the images are embedded in the email
// ..... code .....
// finished finding resource objects build email parts and return to caller
// Add each alternate view to the message.
// add the HTML view using my newly parsed HTML string
ContentType HtmlContentType = new ContentType("text/html; charset=UTF-8");
AlternateView altViewHTML = AlternateView.CreateAlternateViewFromString(HTML, HtmlContentType);
altViewHTML.TransferEncoding = TransferEncoding.QuotedPrintable;
// when I check here the siteEmail.TextEmail holds the CORRECT textual string I want BUT it's not displaying in the sent email
ContentType PlainContentType = new ContentType("text/plain; charset=UTF-8");
// as we didn't need to change anything in the text view we can just reference it straight out my custom email object siteEmail
AlternateView altViewText = AlternateView.CreateAlternateViewFromString(siteEmail.TextEmail, PlainContentType);
altViewText.TransferEncoding = TransferEncoding.QuotedPrintable;
// loop through all my picture resource objects and ensure they are embedded into the HTML email
foreach (LinkedResource pictureResource in pictureResources)
{
pictureResource.TransferEncoding = TransferEncoding.Base64;
altViewHTML.LinkedResources.Add(pictureResource);
}
// add both parts of the email (text/html) which are both alternative views to message
email.AlternateViews.Add(altViewText);
email.AlternateViews.Add(altViewHTML);
// return email object
return email;
}
// a very cut down example of the calling method
public bool SendEmail()
{
// parse our email object
MailMessage EmailMailMessage = this.ParseEmailImages(this.SiteEmail);
// send email
EmailMailMessage.From = new MailAddress(this.SendFromEmail, this.SendFromName);
EmailMailMessage.Subject = this.SendSubject;
// ensure encoding is correct for Arabic/Japanese sites and body transfer method is correct
EmailMailMessage.BodyEncoding = Encoding.UTF8;
EmailMailMessage.BodyTransferEncoding = TransferEncoding.QuotedPrintable;
SmtpClient client = new SmtpClient();
// this in a try catch and more complex
client.Send(this.EmailMailMessage);
}
</pre>
I have tried playing about with the encoding formats, just adding one alternative view and so on but cannot seem to get it to send out the same email as my old ASP Classic code e.g a multipart email with 2 boundaries, 1 for the text version WE WANT TO USE and one with the HTML version. It always seems to create it's own Plain Text version from the HTML version which I don't want to happen.
Any help or ideas would be much appreciated.
Thanks in advance for any help!
The answer seems to be that there is a bug in the MailMessage class. I have been told to report this as such on the Microsoft .NET forum.
It seems that the issue lies in the use of LinkedResources.
If I remove the code that adds the LinkedResources to the HTML alternative view then the code works fine and I can see both my Plain Text and HTML views in my mail client.
Therefore I have to leave the images as externally linked resources that are loaded into the email when the user presses any "load remote content" button in their email client.

To open outlook new email window with content already filled

How can I implement email functionality, where:
When I click on an asp button, a new email window opens with all the content already added from code behind( including To address, From address, Subject and Body).
But the email should not be sent automatically. It requires user to click send button.
The purpose is, admin can modify the email content before sending to users.
Has anyone worked on similar functionality and can help or give me idea on how to implement it ?
Outlook.Application outlookApp = new Outlook.Application ();
Outlook._MailItem mailItem = (Outlook._MailItem)outlookApp.CreateItem ( Outlook.OlItemType.olMailItem );
mailItem.To = address;
// body, bcc etc...
mailItem.Display ( true );
I think you do not need ASP.NET for this. All you need is mailto with the right parameters.
Example:
<a href="mailto:someone#example.com?Subject=Hello%20again&body=This%20is%20body">
Send Mail</a>
This will send email to someone#example.com with subject "Hello" and body "This is body". You can also use CC parameter to add CC emails.
More info on this link
A related question that may help How do I properly encode a mailto link?

How to get the link of attached files in Email?

I want to send an email with some attached images. I also need to show these images in Email. How can I get the link of these attached email so that I can show them in email.
Note: I can also use remote images, but email servers like yahoo, gmail and hotmail will put them in spam.
Is this is possible in ASP.NET or ASP.NET MVC?
Take a look at this question with a solution using the AlternateView class:
sending mail along with embedded image using asp.net
string html = #"<html><body><img src=""cid:YourPictureId""></body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource yourPictureRes = new LinkedResource("yourPicture.jpg", MediaTypeNames.Image.Jpeg);
yourPictureRes.ContentId = "YourPictureId";
altView.LinkedResources.Add(yourPicture);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(altView);

Categories