How to send dymanically generated html as a email attachment in C# - 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");

Related

Send e-mail with image on body

I want to send an e-mail with a logo at the top of the body. This is my method:
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = port;
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
The method is sending the e-mail, but the image is being sent as an attachment. I've tried to do this:
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"), MediaTypeNames.Image.Jpeg);
But when I add "MediaTypeNames.Image.Jpeg" in this line, the e-mail is sent without the image at all.
Someone can help me on this? Thanks in advance!
You could convert your image to base64 and add that in src or you could just give the page where is the image is located.
You could try the library MailKit. Sending embedded images works well with this library.
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Png);
stream.Position = 0;
var resource = builder.LinkedResources.Add(contentId, stream);
resource.ContentId = contentId;
// in the email message, there is img with src="cid:contentId"
Another example of embedding images is here.
You can use it :
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = 0; //add port here
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
//add file here
Attachment attachment = new Attachment("c://image");
attachment.ContentDisposition.Inline = true;
message.Attachments.Add(attachment);
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}

gridview.rendercontrol returns System.Web.UI.HtmlTextWriter

I am trying to send grid in my email, It sends email with a only System.Web.UI.HtmlTextWriter, It does not populate grid.
here is my code:
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
StringBuilder emailBody = new StringBuilder();
StringWriter emailStringWriter = new StringWriter();
HtmlTextWriter htmlGrid = new HtmlTextWriter(new HtmlTextWriter(new StringWriter(emailBody, CultureInfo.InvariantCulture)));
mail.Dispose();
mail = new System.Net.Mail.MailMessage();
mail.To.Add('abc#xyz.com');
mail.From = 'def#yzy.com';
mail.Subject = 'grid example';
myGrid.RenderControl(htmlGrid);
mail.Body = htmlGrid.ToString();
mail.IsBodyHtml = true;
smtp = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["smtpSetting"].ToString());
smtp.Port = 25;
smtp.Send(mail);
mail.Dispose();
I received the email but grid was not there , only this text was there: System.Web.UI.HtmlTextWriter
You need to declare a StringBuilder for your HtmlTextWriter.
StringBuilder sb = new StringBuilder();
HtmlTextWriter htmlGrid = new HtmlTextWriter(new StringWriter(sb, CultureInfo.InvariantCulture));
You may need to flush the writer(not certain), but you will use sb.ToString() to get the rendered html.
mail.Body = sb.ToString();

Send email attachment created in HttpContext.Current.Response

I am creating a pdf using itextsharp. The pdf created normally and post it to the browser so the user can easily save the file to his computer . Now i want this generated pdf automatically send it also with email . I have try to convert the doc before post it to context and attach it to an email but with no any success. My code is:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=mypdf.pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
string imagepath = Server.MapPath(".") + "/assets/myimages/myimage.png";
Document Doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
HTMLWorker htmlparser = new HTMLWorker(Doc);
PdfWriter pdfwriter= PdfWriter.GetInstance(Doc, HttpContext.Current.Response.OutputStream);
Doc.Open();
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
image.ScalePercent(106f,90f);
Doc.Add(image);
//adding elements using itextshart pdf
AddPDf(pdfwriter,Doc);
//to add html in pdf
// htmlparser.Parse(stringReader);
OnEndPage(pdfwriter, Doc);
Doc.Close();
email_send(Doc.ToString());
HttpContext.Current.Response.End();
public void email_send( string filename)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("myemail#gmail.com");
mail.To.Add("reciever#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment((Server.MapPath(filename.ToString())));
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypass");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
The error i get is :
Could not find file
{"Could not find file 'C:\\Admin\\iTextSharp.text.Document'.":"C: \\Admin\\iTextSharp.text.Document"}
The reason for the error is that you're passing the Doc object reference to your email_send method, instead of the file path.
I made a somewhat similar emailing solution by reading the document to a MemoryStream and passing that as the attachment.
public void email_send(Document d)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("myemail#gmail.com");
mail.To.Add("reciever#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.IO.MemoryStream ms = new System.IO.MemoryStream();
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(d, ms);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
Attachment attach = new Attachment(ms, ct);
mail.Attachments.Add(attach);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypass");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
writer.Flush();
writer.Dispose();
ms.Dispose();
}
Call it email_send(Doc).

Use XMLSerializer to stream directly into a MailMessage Attachment

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

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);

Categories