Create eml file in memory without saving it on disk - c#

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.

Related

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.

Creating .xls file and On the Spot will be sent with C#

Currently I just created a program which can send the .xls file, I used google smtp server so I can already sent email with that server in my program. And inside my program, based on my date, I can create .xls file with today date and time. What I want to know is this file will be used to be attachment for the email. How I can do it?
Currently my file name is DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls" so I can create based on today date and time. How I can retrieve the file name to be used as email attachment?
I am assuming you are using the .NET's default Emal api found in the System.Net.Mail namespace.
You can add the file as an attachment to the System.Net.Mail.MailMessage object.
The System.Net.Mail.Attachment class accepts a constructor that can take the stream which you could have used to create the xls file. So, if you create the excel file on the fly, you'll probably already have a reference to the stream where it is written. Then you need to use the code below:
using (Stream myXlsFileStream = new MemoryStream())
{
// assumig you populate the stream like this...
WriteXlsToStream(myXlsFileStream);
myXlsFileStream.Flush();
MailMessage message = new MailMessage();
// configure mail message contents ...
using (Attachment xlsAttachment = new Attachment(
myXlsFileStream,
"FileNameToAppearInEmail.xls",
"application/xls"))
{
message.Attachments.Add(xlsAttachment);
// send the message
}
}
Please, note that the stream must not be closed, and all data should have been written to it. You may need to call myXlsFileStream.Flush() (as in above code) before adding the attachment, in order to ensure that the file is entirely written.

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.

Sending mhtml emails - 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

Categories