Adding a dynamic attachment to an email in c# - 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.

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.

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.

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.

C# Get filename from mail attachements

I have a simple C# app that send SMTP emails (using System.Net.Mail classes). After sending (emailing) a MailMessage object I want to iterate through the list of the attachments and delete the original files associated with those attachments... but I am having a hard time finding the full file path associated with each attachment - without keeping my own collection of attachment filepaths. There has got to be a good way to extract the full file path from the attachment object.
I know this has got to be simple, but I am spending way to much time on this..time to ask others.
If you adding your attachments through the Attachment constructor with filePath argument, these attachments can be retrieved through ContentStream property and will be of type FileStream. Here is how you can get file names of the files attached:
var fileNames = message.Attachments
.Select(a => a.ContentStream)
.OfType<FileStream>()
.Select(fs => fs.Name);
But don't forget to dispose MailMessage object first, otherwise you won't be able to delete these attachments:
IEnumerable<string> attachments = null;
using (var message = new MailMessage())
{
...
attachments = message.Attachments
.Select(a => a.ContentStream)
.OfType<FileStream>()
.Select(fs => fs.Name);
}
foreach (var attachment in attachments )
{
File.Delete(attachment);
}
You can
Read Attachment.ContentStream
If you now have a StreamReader or similar, use the BaseStream property to try and find the inner FileStream
Read FileStream.Name
but bear in mind that the mail message (and hence attachments and their streams) may not get collected or cleaned up immediately, so you may not be able to delete the file straight away. You might do better subclassing Attachment and both record the filename and subclass Dispose (to execute after the base dispose) to do the delete if you really do need to do things this way.
It's generally easiest to take a slightly different tack and attach via a memorystream rather than a file. That way you avoid all the issues around saving the files to disk and cleaning them up afterwards.
Short article here on that.

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