Use XMLSerializer to stream directly into a MailMessage Attachment - c#

I am using an XMLSerializer and I need to write it straight into a Mail Message Attachment preferably without saving it into a file first.
My code
var smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587)
{
Credentials = new System.Net.NetworkCredential("email#gmail.com", "password"),
EnableSsl = true
};
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(XmlRoot));
ser.Serialize(ms, model);
var attachment = new System.Net.Mail.Attachment(ms, "file.xml", "application/xml");
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("tothisemail#gmail.com");
message.Subject = String.Format("{0}", some subject name);
message.From = new System.Net.Mail.MailAddress("email#gmail.com");
message.Body = "empty content";
message.Attachments.Add(attachment);
smtp.Send(message);
What's happening is the email is successfully sent but the xml file it writes to is completely empty.

ser.Serialize(ms, model);
ms.Position = 0;
var attachment = new System.Net.Mail.Attachment(ms, "file.xml", "application/xml");
Writing to then reading from a MemoryStream

Related

How to send dymanically generated html as a email attachment in C#

I am using following code to send email but it is failed if I used html attachment.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer2 = new System.IO.StreamWriter(ms);
writer2.Write("<html><head></head><body>Invoice 1</body></html>");
writer2.Flush();
writer2.Dispose();
MailMessage mm = new MailMessage();
mm.To.Add("test#gmail.com");
mm.CC.Add("test2#gmail.com");
mm.From = new MailAddress("test3#gmail.com");
mm.Subject = "नोटिस";
mm.Body = sb.ToString();
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Html);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "myFile.html";
mm.Attachments.Add(attach);
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "rcms.pdf"));
ms.Close();
mm.IsBodyHtml = true;
only one line needed.
var a = System.Net.Mail.Attachment.CreateAttachmentFromString("‌​'"+sb.ToString()+"'<‌​/body>", "notices.html");

How to put an image file into a MemoryStream and attach it into an Email

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

How do I get my PDF email attachment to attach correctly as a PDF?

Below I've added a screenshot of the attachment as it appears in the email.
It opens fine in any PDF reader.
How do I get it to present as an actual PDF? I feel as though I've missed something small...
Here's my code:
public ActionResult SendInvoice(SendInvoiceViewModel model)
{
var Invoice = db.Invoices.FirstOrDefault(x => x.Id == model.Id);
MemoryStream ms = new MemoryStream(Invoice.Document);
Attachment Data = new Attachment(ms, MediaTypeNames.Application.Pdf);
ContentDisposition Disposition = Data.ContentDisposition;
Disposition.CreationDate = Invoice.Date;
Disposition.ModificationDate = Invoice.Date;
Disposition.ReadDate = Invoice.Date;
SendInvoiceMail(model.EmailAddress, Invoice.Number, model.EmailMessage, Data);
}
private void SendInvoiceMail(string emailAddress, string invoiceNumber, string message, Attachment attachment)
{
using (MailMessage Message = new MailMessage())
{
Message.From = new MailAddress("accounts############");
Message.Subject = String.Format("Your store invoice {0}", invoiceNumber);
Message.To.Add(new MailAddress(emailAddress));
Message.Body = message;
Message.Attachments.Add(attachment);
SmtpClient smtp = new SmtpClient("mail.############", 587);
smtp.Credentials = new NetworkCredential("info###########", "##########");
smtp.Send(Message);
};
}
So what did I miss?
Try using the 3-parameter version of the Attachment() constructor. The second parameter lets you give a file name. That file name should end in .pdf.
Try
public ActionResult SendInvoice(SendInvoiceViewModel model)
{
var Invoice = db.Invoices.FirstOrDefault(x => x.Id == model.Id);
MemoryStream ms = new MemoryStream(Invoice.Document);
//Construct a file name for the attachment
var filename = string.Format("{0}.pdf", Invoice.Number);
Attachment Data = new Attachment(ms, filename, MediaTypeNames.Application.Pdf);
ContentDisposition Disposition = Data.ContentDisposition;
Disposition.CreationDate = Invoice.Date;
Disposition.ModificationDate = Invoice.Date;
Disposition.ReadDate = Invoice.Date;
SendInvoiceMail(model.EmailAddress, Invoice.Number, model.EmailMessage, Data);
}
Where you include the file name for the attachment.

Insert image in email

I'm trying to insert an image in an email following this http://www.codeproject.com/Tips/326346/How-to-embed-a-image-in-email-body
but for some images are not showing in the mail.
Here is the code.
var message = new MailMessage();
message.From = new MailAddress("noreply#happy.com");
message.To.Add("testmail#gmail.com");
var body = new StringBuilder();
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
var path = #"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg";
AlternateView altView = AlternateView.CreateAlternateViewFromString("testing mail: <img src=cid:myImage>", null, MediaTypeNames.Text.Html);
LinkedResource imageToSend = new LinkedResource(path);
imageToSend.ContentId = "myImage";
altView.LinkedResources.Add(imageToSend);
message.AlternateViews.Add(altView);
var smtp = new SmtpClient();
smtp.Send(message);

Email Attachment from memory stream is coming as blank in C#

I am able to send an attachment in a mail but the attachment content is blank and size is being shown as 0 bytes.
After doing some search over the internet found that we need to reset the memory stream position to 0 in order to start from start.
I tried that as well but it seems it is not working. Can you please help?
Please find below my code snippet:
NOTE: I am able to save the workbook and Data is present in the saved workbook.
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream);
writer.Write(xlWorkbook);
writer.Flush();
memoryStream.Position = 0;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpclient");
mail.From = new MailAddress("from#gmail.com");
mail.To.Add("To#gmail.com");
mail.Subject = "Entry";
mail.Body = "Hello, PFA ";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(memoryStream,"xls");
attachment.ContentDisposition.FileName = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
mail.Attachments.Add(attachment);
SmtpServer.Port = 465;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("Username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
writer.Dispose();
I think the attachment is confusing the mail system. Microsoft's recommendation is to specify the content type as an octet. Below is a replacement for initializing the attachment. The reset of your code looks fine.
string filename = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
attachment = new System.Net.Mail.Attachment(memoryStream, filename, MediaTypeNames.Application.Octet);

Categories