Sending mhtml emails - C# - c#

I have a requirement to send emails containing both text and Images.
So, I have .mhtml file that contains the content that needs to be emailed over.
I was using Chilkat for this, but in outlook 2007 it is showing the mhtml file as different attachments(html+images).
Can anyone suggest me some other component for sending mhtml emails.
FYI, I am using .Net 3.5
Also, I do not want to save the images on server before sending them.
Thank you!

I use plain old native MailMessage class. This previous answer can point you in right direction
EDIT: I built a similiar code some time ago, which captures an external HTML page, parse it's content, grab all external content (css, images, etc) and to send that through email, without saving anything on disk.

Here is an example using an image as an embedded resource.
MailMessage message = new MailMessage();
message.From = new MailAddress(fromEmailAddress);
message.To.Add(toEmailAddress);
message.Subject = "Test Email";
message.Body = "body text\nblah\nblah";
string html = "<body><h1>html email</h1><img src=\"cid:Pic1\" /><hr />" + message.Body.Replace(Environment.NewLine, "<br />") + "</body>";
AlternateView alternate = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
message.AlternateViews.Add(alternate);
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream("SendEmailWithEmbeddedImage.myimage.gif")) {
LinkedResource picture = new LinkedResource(stream, MediaTypeNames.Image.Gif);
picture.ContentId = "pic1"; // a unique ID
alternate.LinkedResources.Add(picture);
SmtpClient s = new SmtpClient();
s.Host = emailHost;
s.Port = emailPort;
s.Credentials = new NetworkCredential(emailUser, emailPassword);
s.UseDefaultCredentials = false;
s.Send(message);
}
}

System.Net would be the one that you are looking for.<br/>
MailMessage is used to compose new mail.<br/>
SMTPClient is used to send mail.
NetworkCredentials would be used to attach username and password for making request to sending mail.
Coming to your question how to add images.
You need to set isHtml=true for MailMessage
Since you want to send mail relative paths in the html won't work like ../directory/imagename.formate
in such case you need to give completed path to the image location that's websiteUrl/directory/imagename.formate
To get complete Url dynamically you can use like this Request.Uri.GetLeftParth(URIPartial.Authority)+VitrtualToAbsolute.getAbsolute("~")
I'm not sure about last line since I have wrote directly over here. You just need to use it and have good luck ;-)

You need to explicitly set the MIME type to multipart/related. Change the MailMessage.Body to include the content of the MHTML file in it. Finally add a new item to the MailMessage.AlternateViews collection to define the correct MIME type. The following link from MSDN has a very good example how to set it up:
MailMessage.AlternateViews Property

Related

Create eml file in memory without saving it on disk

I'm working with C# on Windows servers for a web application stored on the IIS Server.
I would like to create an eml file from :
an html content (string)
some attachments that are loaded in memory
a string subject
string recipients
string sender
The main problem is that I am not allowed to store files on the host server (not even in a temporary directory or if I delete them after).
I saw many threads explaining how to create an eml file with the help of SmtpClient. But we always need to use a directory to save the file.
Do someone knows a way to do that ? Or to create a directory in memory (which seems undoable) ?
Thanks for everyone who will read me
[EDIT]
Using jstedfast's answer below and the Mime documentation, I could figure a way. Here is a POC in case someone needs it later.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Joey", "joey#friends.com"));
message.To.Add(new MailboxAddress("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
var builder = new BodyBuilder();
// Set the plain-text version of the message text
builder.TextBody = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.
Will you be my +1?
-- Joey
";
// We may also want to attach a calendar event for Monica's party...
builder.Attachments.Add("test.pdf", attachmentByteArray);
// Now we just need to set the message body and we're done
message.Body = builder.ToMessageBody();
using (var memory = new MemoryStream())
{
message.WriteTo(memory);
}
Look into using MimeKit.
You can write the MimeMessage objects to any type of stream that you want, including a MemoryStream.

Adding a dynamic attachment to an email in c#

Folks,
Using the System.Diagnostics.Process.Start("mailto: method of creating an email, is there a way to add a dynamic attachment (not a saved file) to the email?
I'm pretty much doing the same as this the person in this question but no-one has answered using the mailto: method.
Im just wondering if its possible, and how to do it.
I've tried this but to no avail:
System.IO.MemoryStream ms = new System.IO.MemoryStream(generatedReport.DocumentBytes);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
Attachment attachment = new Attachment(ms, ct);
attachment.ContentDisposition.FileName = "output.pdf";
System.Diagnostics.Process.Start("mailto:myemail &SUBJECT=Test Subject BODY=Body Text&Attachment=" + attachment);
ms.Close();
Any and all help is appreciated
In general, the mailto: URL scheme does not support attachments. Thus, you should not use it at all if you need it to work reliably with attachments.
Apparently, some mail clients still support passing Attachment=..., but they expect the ... part to be the path of a local file. Thus, in your case, you need to
save the file to disk (you can use a temporary file name in a temporary folder) and then
pass the path of the file to your mailto: link.
Note that you will have to keep the file around until the user has actually sent the mail, so you might have to think about "cleaning up" those temporary files at a later time.

Sending an e-mail with an image inline that is attached comes up as ATT00001 on some computers

This is working fine locally but when I sent it to another person in the company (same exchange server) using Outlook on a mac, it does not work correctly. Instead, the image is replaced with the text ATT00001 and the image becomes an attachment called ATT0001
It was tricky to get this working in the first place, here is the code I use:
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream("EmailManager.Kitten.jpg");
var inlineLogo = new LinkedResource(stream, "image/jpg");
inlineLogo.ContentId = "CompanyLogo";
body = body.Replace("{logourl}", string.Format("cid:{0}", inlineLogo.ContentId));
var view = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
view.LinkedResources.Add(inlineLogo);
mailMessage.Body = body;
mailMessage.Subject = "Check out the kitty logo";
mailMessage.AlternateViews.Add(view);
mailMessage.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(....);
smtp.Send(mailMessage);
The body is just a string of stuff with an <img src='{logourl}' /> in it.
Any suggestions of what I might do to fix or debug this? Alternatively is there a way to link to an external image without outlook blocking it by default (eg. having it come from the same server or similar).
Edit: I've read something about macs wanting the attachments listing at the end of the e-mail, could this be it? Although there is no way I can see from the above how to specify this behaviour. Also I am not entirely sure it's the problem.
can be one of the possible solution
i have found answer .bin file comes when _EmailLogo1 and
_EmailLogo are empty so need to check if it's empty/NULL or not !! if not empty/NULL then it should be linked otherwise don't !!
dynamic htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), null, "text/html");
if (!string.IsNullOrEmpty(_EmailLogo1)) {
LinkedResource logo = new LinkedResource(_EmailLogo);
logo.ContentId = "logo2";
htmlView.LinkedResources.Add(logo);
}
if (!string.IsNullOrEmpty(_EmailLogo))
{
LinkedResource logo1 = new LinkedResource(_EmailLogo1);
logo1.ContentId = "logo1";
htmlView.LinkedResources.Add(logo1);
aMessage.AlternateViews.Add(htmlView);
}
Some email clients are smart enough to display correctly whereas others require you to be very specific with your AlternateView and LinkedResource. Have you tried with other email clients e.g. Windows Live Mail?
Try specifying the ContentType of your AlternateView:
view.ContentType = new ContentType("text/html");
I had the same issue where Outlook did the same, displayed the image as an unnamed attachment however Windows Live Mail worked perfectly.
Fast forward to when we moved our SMTP server to Mandrill and we hit the same issue for all email clients where emails displayed as unnamed attachments and it turned out we didn't specify one of our ContentType's and it defaulted to "application/octet-stream"
I know that this question is a bit old, but I have noticed that some issues occur when you use ' instead of " wrapping the source.
Try instead to write it like this <img src="{logourl}" />
Hope this helps someone.

How to open .eml files in the WebBrowser control?

I'd like to ask here, how can I open a .eml file, located in the file system, in a WebBrowser control. Here's what I've at this moment:
string uri = Convert.ToString(myDataReader["Uri"]); //obtained the URI from a database query a few lines of code earlier
FileInfo file = new FileInfo(uri);
OpenPop.Mime.Message mensagem = OpenPop.Mime.Message.Load(file);
origem = mensagem.Headers.From.ToString(); //origin of the email
destino = mensagem.Headers.To.ToString(); //destiny
assunto = mensagem.Headers.Subject.ToString(); //subject
conteudo = mensagem.MessagePart.Body; //message body
I'm using OpenPop.Net to get the messages from the POP3 server in another form, and I need to know how to get the HTML part of those messages...
Thanks in advance!
João Borrego
Have you checked out the examples for OpenPop.Net? Specifically you should check out the "Find specific parts of an email (text, html, xml)" example.
There is a introduction to how email works on the website as well. This might be helpful in understanding how OpenPop.Net is built since it evolves around how emails are structured internally.

Any suggestions for components to implement "Send to a friend"?

I have a webpage which I would like users to be able to send to a friend at the click of a button. I am currently using Chilkat's MailMan but I keep getting intermittent problems with it. It seems occassionaly on the first attempt to mail it throws a null pointer exception. Then if try the exact same page again it sends no problem.
Are there any other components out
there that will do what I am trying
to do?
Would it be easier to right my
own light weight component to do it?
Has anyone had the above problem that
can be solved easily and then I don't
have to worry about the above?
EDIT:
Maybe I should clear something up. I know how to send emails. That is not the problem. The Chilkat component I was using could take in a webpage and put it into an email and send it. The person that receives it then has an email with all the CSS included and the pictures and everything in the email.
This is actually not a trivial exercise.
What you want to do, is download the HTML (which is the easy part). You then have to parse it, and extract all of the css references, and image references, and either:
Embed them into the email, or
Convert all links to absolute links.
When you look at all the bad HTML out there, you find out this isn't trival. The reason why I know this, is I wrote this functionality into aspNetEmail (www.aspNetEmail.com), and had to account for all sorts of bad HTML.
Could you use the WebClient class to get the webpage that the user is requesting? You'd want to change any relative links to absolute links (e.g. from "/images/logo.gif" to "http://myapp.com/images/logo.gif"), then take the output and use that as the body of the MailMessage object
i.e.
public void MailToAFriend(string friendMailAddress, Uri uriToEmail) {
MailMessage message = new MailMessage();
message.From = "your_email_address#yourserver.com";
message.To = friendEmailAddress;
message.Subject = "Check out this awesome page!";
message.Body = GetPageContents(uriToEmail);
SmtpClient mailClient = new SmtpClient();
mailClient.Send(message);
}
private string GetPageContents(Uri uri) {
var webClient = new WebClient();
string dirtyHtml = webClient.DownloadString(uri);
string cleanedHtml = MakeReadyForEmailing(dirtyHtml);
return cleanedHtml;
}
private string MakeReadyForEmailing(string html) {
// some implementation to replace any significant relative link
// with absolute links, strip javascript, etc
}
There's lots of resources on Google to get you started on the regex to do the replacement.
1) .NET comes with a reasonably adequate class for sending mail, in System.Net.Mail.
2) If it happens only rarely and does not repeat, just put it in a try block and retry two more times before considering it a failure. While it may sound crude, it's a very effective solution.

Categories