In my project i need to attach multiple files to send mail and i am doing it as
if (fDialog.ShowDialog() == DialogResult.OK)
{
textBox6.Text += fDialog.FileName.ToString() + ";";
}
Here i am attaching the file in textbox6
I am separating the paths of the different attachment file using ";" and then i separate those paths of the attachment as follows and then send it.
System.Net.Mail.Attachment attachment;
foreach (string m in textBox6.Text.Split(';'))
{
attachment = new System.Net.Mail.Attachment(m);
message.Attachments.Add(attachment);
}
This method don't work for me. But when i send mail with single attachment with the following code it just work fine
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(textBox6.Text.ToString());
message.Attachments.Add(attachment);
Someone please help. I have been working this whole day and could not figure it out.
I hope this will solve your problem completely http://archive.msdn.microsoft.com/CSharpGmail
The function should be :
foreach (string m in textBox6.Text.Split(';'))
{
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(m);
message.Attachments.Add(attachment);
}
This will fix your issue.
Try to use file stream instead of link on file:
message.Attachments.Add(new Attachment(attachmentFileStream, fileNameOnly));
Create a Attachmentlistbox then-
if (Attachmentlistbox.Items.Count != 0)
{
for (int i = 0; i < Attachmentlistbox.Items.Count; i++)
mailMessage.Attachments.Add(new Attachment(Attachmentlistbox.Items[i].ToString()));
}
Related
I am working on code in C#,but not going through on thing that is I have saved some .eml file on my disk now I am parsing each eml file and creating a new mail adding the eml file data to the new mail but I am unable to attach the attachments present in the .eml file to the new mail , can anybody please help?
I am using the follwing code but it shows the error ex = {"The process cannot access the file because it is being used by another process.\r\n":null}
foreach (CDO.IBodyPart attach in msg.Attachments)
{
i++;
string filenm = "C:\\mail_automation\\attachments\\xyz" + i +".eml";
if (File.Exists(filenm))
{
string fn = attach.FileName;
attach.SaveToFile("C:\\mail_automation\\attachments\\xyz" + i + ".eml");
Attachment data = new Attachment(filenm);
mailMessage.Attachments.Add(data);
}
else
{
File.Create(filenm);
string fn = attach.FileName;
attach.SaveToFile("C:\\mail_automation\\attachments\\xyz" + i + ".eml");
Attachment data = new Attachment(filenm);
mailMessage.Attachments.Add(data);
}
You have to extract the attachments and save them to disk first, then fetch it again into the new mail.
Code example here
MailMessage message = new MailMessage();
MemoryStream ms = new MemoryStream(); //store the mail into this ms 'memory stream'
ms.Position = 0;
message.Attachments.Add(new Attachment(ms, attachmentName));
I'm trying to learn how to use the MailKit library but I am struggling to retrieve attachments. So far my code will open a mailbox, go through each message and store data such as sender, subject, body, date etc. but I can't deal with attachments.
I have tried to use other peoples solutions found on here, on github and other sites but I still don't understand exactly what they are doing in their code and when I come close to getting a solution working it causes more bugs so I get stressed and delete all the code. I don't mean to seem lazy but I would love if somebody could explain how I can achieve this. I'm basically trying to build a mail client for a web forms app.
Below is my code, so as you can see I'm fairly clueless :)
// Open the Inbox folder
client.Inbox.Open(FolderAccess.ReadOnly, cancel.Token);
//get the full summary information to retrieve all details
var summary = client.Inbox.Fetch(0, -1, MessageSummaryItems.Full, cancel.Token);
foreach (var msg in summary)
{
//this code originally downloaded just the text from the body
var text = msg.Body as BodyPartText;
//but I tried altering it so that it will get attachments here also
var attachments = msg.Body as BodyPartBasic;
if (text == null)
{
var multipart = msg.Body as BodyPartMultipart;
if (multipart != null)
{
text = multipart.BodyParts.OfType<BodyPartText>().FirstOrDefault();
}
}
if (text == null)
continue;
//I hoped this would get the messages where the content dispositon was not null
//and let me do something like save the attachments somewhere but instead it throws exceptions
//about the object reference not set to an instance of the object so it's very wrong
if (attachments.ContentDisposition != null && attachments.ContentDisposition.IsAttachment)
{
//I tried to do the same as I did with the text here and grab the body part....... but no
var attachedpart = client.Inbox.GetBodyPart(msg.Index, attachments, cancel.Token);
}
else
{
//there is no plan b :(
}
// this will download *just* the text
var part = client.Inbox.GetBodyPart(msg.Index, text, cancel.Token);
//cast main body text to Text Part
TextPart _body = (TextPart)part;
I'm not entirely clear on what you want to accomplish, but if you just want to download the message attachments (without downloading the entire message) and save those attachments to the file system, here's how you can accomplish that:
var messages = client.Inbox.Fetch (0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId);
int unnamed = 0;
foreach (var message in messages) {
var multipart = message.Body as BodyPartMultipart;
var basic = message.Body as BodyPartBasic;
if (multipart != null) {
foreach (var attachment in multipart.BodyParts.OfType<BodyPartBasic> ().Where (x => x.IsAttachment)) {
var mime = (MimePart) client.Inbox.GetBodyPart (message.UniqueId.Value, attachment);
var fileName = mime.FileName;
if (string.IsNullOrEmpty (fileName))
fileName = string.Format ("unnamed-{0}", ++unnamed);
using (var stream = File.Create (fileName))
mime.ContentObject.DecodeTo (stream);
}
} else if (basic != null && basic.IsAttachment) {
var mime = (MimePart) client.Inbox.GetBodyPart (message.UniqueId.Value, basic);
var fileName = mime.FileName;
if (string.IsNullOrEmpty (fileName))
fileName = string.Format ("unnamed-{0}", ++unnamed);
using (var stream = File.Create (fileName))
mime.ContentObject.DecodeTo (stream);
}
}
Another alternative that works for me, but appears to be a little simpler:
var messages = client.Inbox.Fetch (0, -1, MessageSummaryItems.Full | MessageSummaryItems.BodyStructure | MessageSummaryItems.UniqueId);
int unnamed = 0;
foreach (var message in messages) {
foreach (var attachment in message.Attachments) {
var mime = (MimePart) client.Inbox.GetBodyPart (message.UniqueId.Value, attachment);
var fileName = mime.FileName;
if (string.IsNullOrEmpty (fileName))
fileName = string.Format ("unnamed-{0}", ++unnamed);
using (var stream = File.Create (fileName))
mime.ContentObject.DecodeTo (stream);
}
}
Note that this is asking for the BODYSTRUCTURE instead of the BODY in the Fetch statement, which seems to fix the issue of attachments not being flagged as such.
I'm using Mail.dll from limilabs to manage an IMAP folder.
There is one mail with an attachment that is an eml file, so a mail.
It has in turn one attached eml file that I need to extract.
So the email structure is as follows:
Email
|- Attachment: file.eml
|- Attachment file2.eml
This is my code:
IMail email = new MailBuilder().CreateFromEml(imap.GetMessageByUID(uid));
Console.WriteLine(email.Subject);
// save all attachments to disk
foreach(MimeData mime in email.Attachments)
{
if (uid == 1376)
{
System.IO.Directory.CreateDirectory(string.Format(#"c:\EMAIL\{0}", uid));
mime.Save(#"c:\EMAIL\" + uid + "\\" + mime.SafeFileName);
MimeData help;
if (mime.ContentType.ToString() == "message/rfc822")
{
//i need to cast this attach in a imail
}
}
}
How can I extract the inner-most eml file (file2.eml in the structure mentioned above)?
From this link, it looks like you should be able to do the following:
if (attachment.ContentType == ContentType.MessageRfc822)
{
string eml = ((MimeText)attachment).Text;
IMail attachedMessage = new MailBuilder().CreateFromEml(eml);
// process further
}
If you only need to extract all attachments from all inner messages, you can use IMail.ExtractAttachmentsFromInnerMessages method:
IMail email = new MailBuilder().CreateFromEml(imap.GetMessageByUID(uid));
ReadOnlyCollection<MimeData> attachments = mail.ExtractAttachmentsFromInnerMessages();
foreach (MimeData mime in attachments)
{
mime.Save(#"c:\" + mime.SafeFileName);
}
I have created an application that generates excel files from information in a database. These files are saved on my HDD in a folder.
After that I attach the files and send them via mail. When I generate another batch of files I delete the old files and then create the new ones.
My problem is when I have generated one batch of files and then send them, and I want to generate another batch I cannot delete the one of the old files, because the mailing method is still holding on to one of the excel files.
Here is my code:
public void SendMailedFilesDKLol() {
string[] sentFiles=Directory.GetFiles(some_Folder);
if(sentFiles.Count()>0) {
System.Net.Mail.SmtpClient client=new System.Net.Mail.SmtpClient("ares");
System.Net.Mail.MailMessage msg=new System.Net.Mail.MailMessage();
msg.From=new MailAddress("system#lol.dk");
msg.To.Add(new MailAddress("lmy#lol.dk"));
msg.Subject="IBM PUDO";
msg.Body=
sentFiles.Count()+" attached file(s) has been sent to the customer(s) in question ";
msg.IsBodyHtml=true;
foreach(string file in sentFiles) {
Attachment attachment=new Attachment(file);
msg.Attachments.Add(attachment);
}
client.Send(msg);
}
}
I have tried to dispose the client element but that didn't help.
Can anyone help me with this?
Both System.Net.Mail.MailMessage & System.Net.Mail.SmtpClient are IDisposable classes. You can try the following,
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("ares"))
{
using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage())
{
msg.From = new MailAddress("system#lol.dk");
msg.To.Add(new MailAddress("lmy#lol.dk"));
msg.Subject = "IBM PUDO";
msg.Body = sentFiles.Count() + " attached file(s) has been sent to the customer(s) in question ";
msg.IsBodyHtml = true;
foreach (string file in sentFiles)
{
Attachment attachment = new Attachment(file);
msg.Attachments.Add(attachment);
}
client.Send(msg);
}
}
It sounds like you may not be closing your file stream when generating the excel files or you have them open in excel when trying to email them.
Please can you show your code for generating the excel files.
You need to dispose the Attachment objects.
Example using LINQ:
public void SendMailedFilesDKLol() {
string[] sentFiles=Directory.GetFiles(some_Folder);
if(sentFiles.Count()>0) {
System.Net.Mail.SmtpClient client=new System.Net.Mail.SmtpClient("ares");
System.Net.Mail.MailMessage msg=new System.Net.Mail.MailMessage();
msg.From=new MailAddress("system#lol.dk");
msg.To.Add(new MailAddress("lmy#lol.dk"));
msg.Subject="IBM PUDO";
msg.Body=
sentFiles.Count()+" attached file(s) has been sent to the customer(s) in question ";
msg.IsBodyHtml=true;
var attachments = sentFiles.Select(f => new Attachment(f)).ToList();
attachments.ForEach(a => msg.Attachments.Add(a));
client.Send(msg);
attachments.ForEach(a => a.Dispose());
}
}
I have the following code that basically attaches a file to an email message then after all attachments are attached and email is sent, i try to delete all files, however I get a file in use exception. I believe the error comes in this line
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
I tried using this code but I get an cannot sent email message
using Attachment data = new Attachment(file, MediaTypeNames.Application.Octet)){
//and the rest of the code in here.
}
foreach (KeyValuePair<string, string> kvp in reports) {
browser.GoTo(kvp.Value);
Thread.Sleep(1000);
System.IO.File.Move(#"C:\Reports\bidata.csv", #"C:\Reports\"+kvp.Key.ToString()+".csv");
string file = #"C:\Reports\" + kvp.Key.ToString() + ".csv";
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
mail.Attachments.Add(data);
}
smtpserver.Send(mail);
string[] files = Directory.GetFiles(#"C:\Reports");
foreach (string files1 in files)
{
File.Delete(files1);
}
In order to delete the files first you will have to dispose the attachment and mail objects and then delete the files
Dispose the smtpclient by putting it in a usings or calling dispose directly. That should free the file resource and allow you to nuke it.