I have created a method that collect every file in a folder and then inserts them into a zip file. The zip file is then sent via mail to a customer. My problem is that I can send a mail message with the zip file attached without any problems, But if another user generates the zip file and sends it, it will look like this.
I had the same issue when trying to attach excel files to a mail message. But i found out that you have to set a ContentType of the files you attach. And after adding this line: ContentType ct = new ContentType("application/vnd.ms-excel"); for the excel files it worked.
My problem is that i am trying to attach a zip file now, i am using this line: `ContentType ct = new ContentType("application/zip"); but this doesnt work. I am using DotNetZipLib-DevKit-v1.9 to add files into a zip file.
this is my code:
public void SendMailedFilesVallensbaek()
{
string[] vallensbeakFileNames = Directory.GetFiles(vallensbaekFiles);
if (vallensbeakFileNames.Count() > 0)
{
ContentType ct = new ContentType("application/zip");
string zipFile = vallensbaekFiles+#"\someZipFile.zip";
using (ZipFile zip = new ZipFile())
{
foreach (string file in vallensbeakFileNames)
{
zip.AddFile(file);
}
zip.Save(zipFile);
}
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#mail.dk");
msg.To.Add(new MailAddress("lmy#mail.dk "));
msg.Subject = "IBM PUDO";
msg.Body = "Best Regards";
msg.Body += "<br/>";
msg.Body += "me";
msg.IsBodyHtml = true;
Attachment attachment = new Attachment(zipFile, ct);
msg.Attachments.Add(attachment);
//foreach (string file in sentFiles)
//{
// Attachment attachment = new Attachment(file, ct);
// msg.Attachments.Add(attachment);
//}
client.Send(msg);
client.Dispose();
msg.Dispose();
ct = null;
}
}
}
}
You should check the zip file is created in your local folder or not
and your local folder is able to access by ASP.NET users.
Related
I am developing a Windows Background Service with .NET and C#. It periodically queries a REST API and sends emails if certain conditions are met. Sometimes the data returned from the API will have image files and sometimes not. When image files are returned, the service embeds them into the email body before sending. I'm embedding the image file in four steps:
Download the image as a byte[]
Convert byte[] to MemoryStream
pass the stream to a new LinkedResource
Add the linked resource to the AlternateView for the MailMessage
This works if the message has a single "To" recipient and no CC or BCC recipients. The image displays correctly in the body of the email. The weird problem I'm having is that if I add multiple recipients in To, CC or BCC, the image fails to display in the email body. This problem seems to be limited to Outlook. I did a test with two recipients, one internal to the organization and one Gmail account. The image displayed correctly in Gmail but was broken in Outlook.
Here is the snippet of code where the service builds the LinkedResource and sends the email.
htmlBody = htmlBody.Replace("{incident_time}", incident.IncidentTime)
.Replace("{incident_type}", incident.IncidentType)
.Replace("{incident_location}", incident.IncidentLocation)
.Replace("{reporting_agency}", incident.ReportingAgency)
.Replace("{severity}", incident.Severity)
.Replace("{details}", incident.Details);
// embed attached images
var attachmentsResult = await arcGisRestClient.QueryAttachmentsAsync(
incidentSublayerUrl,
tokenResponse.Token,
objectId: incident.ObjectId);
IList<LinkedResource> linkedResources = new List<LinkedResource>();
if (!string.IsNullOrEmpty(attachmentsResult))
{
var attachmentsObj = JObject.Parse(attachmentsResult);
var attachments = FeatureAttachmentConverter.FromJObject(attachmentsObj);
// if attachments > 0
if (attachments.Count > 0)
{
string imgHtml = "";
foreach (var attachment in attachments)
{
string attachmentUrl = $"{incidentSublayerUrl}/{attachment.ParentObjectId}/attachments/{attachment.Id}?token={tokenResponse.Token}";
WebClient webClient = new WebClient();
byte[] bytes = webClient.DownloadData(attachmentUrl);
MemoryStream stream = new MemoryStream(bytes);
LinkedResource linkedResource = new LinkedResource(stream, MediaTypeNames.Image.Jpeg);
imgHtml += #"<img src='cid:" + linkedResource.ContentId + #"' width='450'/>";
linkedResources.Add(linkedResource);
}
htmlBody = htmlBody.Replace("{attachments}", imgHtml);
}
else
{
htmlBody = htmlBody.Replace("{attachments}", "");
}
}
AlternateView htmlAlternate = AlternateView.CreateAlternateViewFromString(htmlBody, new ContentType(MediaTypeNames.Text.Html));
foreach (var lr in linkedResources)
{
htmlAlternate.LinkedResources.Add(lr);
}
// create email
MailMessage message = new MailMessage
{
Subject = "TEST Incident Notification",
};
message.AlternateViews.Add(htmlAlternate);
string[] emailToAddresses = _config.GetSection("EmailNotificationTo").Get<string[]>();
message.To.Add(string.Join(',', emailToAddresses));
string[] emailCcAddresses = _config.GetSection("EmailNotificationCc").Get<string[]>();
message.CC.Add(string.Join(',', emailCcAddresses));
message.From = new MailAddress(_config["EmailNotificationFrom"]);
// send email
SmtpClient smtpClient = new SmtpClient("mail.domain.org", 25);
using (smtpClient)
{
smtpClient.Send(message);
logger.Info($"Email notification sent; objectid: {incident.ObjectId}");
}
Could this be an issue with our internal STMP server or Outlook settings rather than a problem with the above code?
I am created a report viewer using rdlc report system. but the problem is got, when I send this file by email then I found an error. My program is something like that:-
at first, I created a reporting process, which shows my "Order" database's all information. that information shows me as one file system on my desktop when I run my application. this file, I want to send by email. but when I trying to send this, I found many errors.
Here is my code:-
public async Task<IActionResult> CheckOut(Order11 anOrder)
{
//other code
//report process
string mimetype = "";
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\Report2.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
var products = _db.Order.ToList();
LocalReport localReport = new LocalReport(path);
localReport.AddDataSource("DataSet1", products);
var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimetype);
var s= File(result.MainStream, "application/pdf");
//report process end
//Email Sender start
var email = anOrder.Email;
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Ghatia Bazar",
"pri#gmail.com"));
message.To.Add(new MailboxAddress("pritom", email));
message.Subject = "Order Details";
message.Body = new TextPart("plain")
{
Text = "Hi,Thanks For Order.",
};
//add attach
MemoryStream memoryStream = new MemoryStream();
BodyBuilder bb = new BodyBuilder();
using (var wc = new WebClient())
{
bb.Attachments.Add("s",
wc.DownloadData("path"));
}
message.Body = bb.ToMessageBody();
//end attach
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("pri#gmail.com",
"MyPassword");
client.Send(message);
client.Disconnect(true);
}
//Email sender end
//other code
I also use bb.Attachments.Add("s", result.MainStream); instead of bb.Attachments.Add("s", wc.DownloadData("path")); when I use this, then I found an unexpected email. In this email's file, I found a lot of code. so now bb.Attachments.Add("s", wc.DownloadData("path")); I am using this process to attach a file. but here I found a different error.
Here is my output:-
How I will solve this problem.How I send my created file by email. I am still a beginner, please help.
From the code it looks like you are using AspNetCore.Reporting library for generating reports from RDLC files.
Code of this library is available on GitHub at https://github.com/amh1979/AspNetCore.Reporting
LocalReport class from this library has Execute method which return an instance of ReportResult class.
Code of both these classes is located at https://github.com/amh1979/AspNetCore.Reporting/blob/master/AspNetCore.Reporting/LocalReport.cs
ReportResult class has a Property MainStream which represents the content of the report as Byte Array.
Now, attachment to MimeMessage via BodyBuilder support various inputs for file contents such as Stream, byte[] etc.
With this knowledge, I think you can directly use ReportResult.MainStream to attach file to the BodyBuilder.
You can change your code as following to make it working.
var path = $"{this._webHostEnvironment.WebRootPath}\\Reports\\Report2.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
var products = _db.Order.ToList();
LocalReport localReport = new LocalReport(path);
localReport.AddDataSource("DataSet1", products);
//Following line of code returns an instance of ReportResult class
var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimetype);
var email = anOrder.Email;
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Ghatia Bazar", "pri#gmail.com"));
message.To.Add(new MailboxAddress("pritom", email));
message.Subject = "Order Details";
message.Body = new TextPart("plain")
{
Text = "Hi,Thanks For Order.",
};
var bb = new BodyBuilder();
// Following line will attach the report as "MyFile.pdf".
// You can use filename of your choice.
bb.Attachments.Add("Myfile.pdf", result.MainStream);
message.Body = bb.ToMessageBody();
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("pri#gmail.com", "MyPassword");
client.Send(message);
client.Disconnect(true);
}
I hope this will help you resolve your issue.
Please I have a working code which send mails correctly only when I execute the application from visual studio, but when I generate the .exe file and install it, I'm not able to recieve the email ! I think it's not problem coming from code, but maybe something else.
a PDF file generated using NReco.Generator and attached to each mail (it's not problem of access because i'm able to send the same files to Box without problem).
What can be the problem ? everything working well in Visual Studio, but not after installing !
This is the code to generate and send file :
void EnvoyerDOCAsync(string path)
{
SmtpClient MyMail = new SmtpClient(ConfigurationManager.AppSettings["server"], Convert.ToInt16(ConfigurationManager.AppSettings["port"]));
MyMsg = new MailMessage();
MyMsg.Priority = MailPriority.High;
MyMsg.From = new MailAddress(ConfigurationManager.AppSettings["mail"], "Sesrvice Mailing");
foreach (Fonction item in fonction.getFonctions())
{
MyMsg.To.Add(new MailAddress(item.FonctionMail, item.FonctionName));
}
MyMsg.Subject = "Hello";
MyMsg.Body = "Bonjour";
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.BodyEncoding = Encoding.UTF8;
MyMail.UseDefaultCredentials = false;
MyMail.Timeout = (60 * 5 * 1000);
NetworkCredential MyCredentials = new NetworkCredential(ConfigurationManager.AppSettings["sso"], ConfigurationManager.AppSettings["pass"]);
MyMail.Credentials = MyCredentials;
if (File.Exists(path))
{
if (path != null)
{
Attachment attachment = new Attachment(path, MediaTypeNames.Application.Octet);
System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(path);
disposition.ModificationDate = File.GetLastWriteTime(path);
disposition.ReadDate = File.GetLastAccessTime(path);
disposition.FileName = Path.GetFileName(path);
disposition.Size = new FileInfo(path).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
MyMsg.Attachments.Add(attachment);
MyMail.SendAsync(MyMsg, null);
MyMail.SendCompleted += MyMail_SendCompleted;
}
}
}
//Execute this after mail is sended to dispose the Msg and show validation message.<br/>
private void MyMail_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
MyMsg.Dispose();
MessageBox.Show("The mail was sended succesfully", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Thank you.
Is it possible to send a directory through email?
I'm using this method to send a log file to my email, but I want to send a directory which would be the save game folder of the game I'm working on in Unity.
I'm using this as a bug report, as I need to get the game save files to find bugs.
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
If it's not possible to send a directory what is the workaround to achieve that?
You may zip the complete directory contents and send the archive file as attachment.
A workaround: just zip it and send as file.
The GZip Class of .NET might just be what you want! MSDN Link
The Compression Snippet right off of there
public static void Compress(DirectoryInfo directorySelected)
{
foreach (FileInfo fileToCompress in directorySelected.GetFiles())
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) &
FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream,
CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
}
}
FileInfo info = new FileInfo(directoryPath + "\\" + fileToCompress.Name + ".gz");
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), info.Length.ToString());
}
}
}
}
You could also use the standard Zipping class from here ZipFile
I encrypted an image,
Now I need to read that image, decrypt and attach it into an email.
For first step I try to put an image file and attach it into an Email,
but when i receive email, the attached image is corrupted !
I try many different ways, but without success.
(I created windows application project just for test, Eventually I need to use solution in MVC Web Application project)
private void btnSend_Click(object sender, EventArgs e)
{
var filePath = "D:\\3.jpg"; // path to none encrypted image file
var ms = new MemoryStream(File.ReadAllBytes(filePath));
// Create attachment
var attach = new Attachment(ms, new ContentType(MediaTypeNames.Image.Jpeg));
attach.ContentDisposition.FileName = "sample.jpg";
// Send Email
IMailSender mailSender = new MailSender();
var isSuccess = mailSender.Send(
"sample email title",
"sample#gmail.com",
"sample subject",
"sample body",
new Attachment[] { attach });
MessageBox.Show(isSuccess ? "Email sent successfully" : mailSender.ErrorMessage);
}
using (MailMessage Message = new MailMessage())
{
Message.From = new MailAddress("from#mail.com");
Message.Subject = "My Subject";
Message.Body = "My Body";
Message.To.Add(new MailAddress("to#mail.com"));
//Attach more file
foreach (var item in Attachment)
{
MemoryStream ms = new MemoryStream(File.ReadAllBytes(filePath));
Attachment Data = new Attachment(ms, "FileName");
ContentDisposition Disposition = Data.ContentDisposition;
Disposition.CreationDate = DateTime.UtcNow.AddHours(-5);
Disposition.ModificationDate = DateTime.UtcNow.AddHours(-5);
Disposition.ReadDate = DateTime.UtcNow.AddHours(-5);
Data.ContentType = new ContentType(MediaTypeNames.Application.Pdf);
Message.Attachments.Add(Data);
}
SmtpClient smtp = new SmtpClient("SmtpAddress", "SmtpPort");
smtp.Credentials = new NetworkCredential("SmtpUser", "SmtpPassword");
await smtp.SendMailAsync(Message);
}
I hope this helps