send multi line txt doc content in an email body message+c# - c#

I am trying to read a multi line txt document and trying to send an email message with the same multi line content as in the text document using c#
I tried using the File.ReadAllText method but that reads the entire txt document content in one string and puts it in the email body without the line separation.
Let's say a txt doc has the following lines
a
bcd
efgh
I want the mail message to be sent in the same format.
Code Specific to Send email is,
mail.IsBodyHtml = true;
mail.Body = File.ReadAllText(path);
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "abc";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.DeliveryMethod = system.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("", "");
}
smtp.Send(mail);

Please, use StreamReader instance with ReadLine() method to read document line by line. Also you can use newline separator to format your document in right way.

Related

How do I include XML in an email body using mailmessage.body

I have an application that performs some tests. As a result of these tests an XML object is produced (from an XmlDiff compare).
Is there any way to embed the XML into an Email body in a formatted state?
I am using XmlWriter to a StringBuilder object then converting the string into and "html safe" format using System.Security.SecurityElement.Escape(). In the MailMessage, I set IsBodyHtml = true.
To extract the XML I want to embed:
public static string GetDiff(string approvedfile, string failingfile)
{
StringBuilder sb = new StringBuilder();
XmlWriter xmlwriter = XmlWriter.Create(sb);
XmlDiff xdiff =
new XmlDiff(XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreNamespaces |
XmlDiffOptions.IgnorePrefixes);
bool response = xdiff.Compare(approvedfile, failingfile, false, xmlwriter);
xmlwriter.Flush();
xmlwriter.Close();
return System.Security.SecurityElement.Escape(sb.ToString());
}
To set the body content I am using:
string sb = GetDiff(approvedMapfile, fileout);
string message = String.Format("Comparison of Map item1 and Map item2 for {0} failed.</br>Review the differences here:</br>{1}</br> and Compare the files</br>{2}</br>and</br>{3}</br>to find the differences.", loc, sb, emailApprovedMap, emailFailedMap);
Util.SendStatusEmail(message);
in SendStatusEmail the mail information is being set thusly:
public static string SendStatusEmail(string status)
{
string hostServer = "smtphost.this.server.com";
MailMessage mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = hostServer;
client.Credentials = CredentialCache.DefaultNetworkCredentials;
MailAddress from = new MailAddress("me#here.com", "Me There");
mail.From = from;
mail.To.Add("You#there.com");
mail.IsBodyHtml = true;
mail.Body = status;
mail.Subject = "Map Checker status report";
try
{
client.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return string.Empty;
}
When the email is received using the above methodology, the embedded XML is included, but it is not formatted, it appears as one long string of XML.
Is there a way to programmatically embed XML in an email body and have it appear as formatted?
Thanks for your help!
I found solution, in the last of the body message create one div and set style display none, not insert close div only open tag div with style display none.
mail.IsBodyHtml = false;
does the job, unless you really need html formatted body.
Maybe is too old but i have solution to just encode the xml text.
refer how to do on C#: How to encode the ampersand if it is not already encoded?
Basically having lib to do this:
HttpUtility.HtmlEncode(string)
i'm doing with java something like this:
StringEscapeUtils.escapeHtml4("<xml><row>1</row></xml>");

Get file to send as attachment from byte array

I have an ASP.NET MVC application that has to send an email to a list of recipients with an attachment detailing a specific "Project". I get the details for this from a report by making use of SQL Server Reporting Services (SSRS).
I've never really used SSRS before, but I received some code from a colleague where he used it. What he does with the report is he downloads it in the browser to the client's machine. So, if I don't do that I sit with a byte array containing the report data.
Is there a way I can send this as an attachment without first physically writing the file to the filesystem of the server? The report will either be in excel format or a pdf.
Edit: I am using SmtpClient to send the email's.
Get the file data in a byte[]
byte[] binaryFile = // get your file data from the SSRS ...
string filename = "SSRS.pdf";
Prepare a list or array of the destination addresses:
string[] addresses = // get addresses somehow (db/hardcoded/config/...)
sending smtp message through SmtpClient:
MailMessage mailMessage= new MailMessage();
mailMessage.From = new MailAddress("sender email address goes here");
// Loop all your clients addresses
foreach (string address in addresses)
{
mailMessage.To.Add(address);
}
mailMessage.Subject = "your message subject goes here";
mailMessage.Body = "your message body goes here";
MemoryStream memoryStream = new MemoryStream(binaryFile);
mailMessage.Attachments.Add( new Attachment( memoryStream, filename , MediaTypeNames.Application.Pdf ));
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
to do this you would need to leverage off the SSRS ReportManager API as follows.
First read in the report from the Web Service with SSRS
Read the file into memory rather than saving to the server or client
Send the MemoryStream object straight to the email server.
Reporting services: Get the PDF of a generated report
How to send an email with attachments using SmtpClient.SendAsync?
string strReportUser = "RSUserName";
string strReportUserPW = "MySecretPassword";
string strReportUserDomain = "DomainName";
string sTargetURL = "http://SqlServer/ReportServer?" +
"/MyReportFolder/Report1&rs:Command=Render&rs:format=PDF&ReportParam=" +
ParamValue;
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create( sTargetURL );
req.PreAuthenticate = true;
req.Credentials = new System.Net.NetworkCredential(
strReportUser,
strReportUserPW,
strReportUserDomain );
HttpWebResponse HttpWResp = (HttpWebResponse)req.GetResponse();
Stream fStream = HttpWResp.GetResponseStream();
HttpWResp.Close();
//Now turn around and send this as the response..
ReadFullyAndSend( fStream );
ReadFullyAnd send method.
NB: the SendAsync call so your not waiting for the server to send the email completely before you are brining the user back out of the land of nod.
public static void ReadFullyAndSend( Stream input )
{
using ( MemoryStream ms = new MemoryStream() )
{
input.CopyTo( ms );
MailMessage message = new MailMessage("from#foo.com", "too#foo.com");
Attachment attachment = new Attachment(ms, "my attachment",, "application/vnd.ms-excel");
message.Attachments.Add(attachment);
message.Body = "This is an async test.";
SmtpClient smtp = new SmtpClient("localhost");
smtp.Credentials = new NetworkCredential("foo", "bar");
smtp.SendAsync(message, null);
}
}

Best way for sending advance email

I'd like to send email by asp.net . I use this code and it is work fine.
mail.From = new MailAddress("mail#gmail.com", "sender", System.Text.Encoding.UTF8);
string to = Session["Umail"].ToString();
mail.To.Add(to);
mail.IsBodyHtml = true;
mail.SubjectEncoding = Encoding.UTF8;
mail.BodyEncoding = Encoding.GetEncoding("utf-8");
mail.Subject = "subject";
mail.Body = "body" ;
SmtpClient smtp = new SmtpClient("Smtp.gmail.Com", 587);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("mail#gmail.com", "pass"); smtp.Send(mail);
But I'd like a custom and beautiful mail. Like emails that send from facebook, google team and etc. I know that can use html tag in mail.Body but is it good way? What is the best way ?
This is ready to use code snippet which I use for sending email which contains both text content and the content based on a html template:
// first we create a plain text version and set it to the AlternateView
// then we create the HTML version
MailMessage msg = new MailMessage();
msg.From = new MailAddress("from#email", "From Name");
msg.Subject = "Subject";
msg.To.Add("to#email");
msg.BodyEncoding = Encoding.UTF8;
String plainBody = "Body of plain email";
//first we create the text version
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
msg.AlternateViews.Add(plainView);
//now create the HTML version
MailDefinition message = new MailDefinition();
message.BodyFileName = "~/MailTemplates/template1.htm";
message.IsBodyHtml = true;
message.From = "from#email";
message.Subject = "Subject";
//Build replacement collection to replace fields in template1.htm file
ListDictionary replacements = new ListDictionary();
replacements.Add("<%USERNAME%>", "ToUsername");//example of dynamic content for Username
//now create mail message using the mail definition object
//the CreateMailMessage object takes a source control object as the last parameter,
//if the object you are working with is webcontrol then you can just pass "this",
//otherwise create a dummy control as below.
MailMessage msgHtml = message.CreateMailMessage("to#email", replacements, new LiteralControl());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");
//example of a linked image
LinkedResource imgRes = new LinkedResource(Server.MapPath("~/MailTemplates/images/imgA.jpg"), System.Net.Mime.MediaTypeNames.Image.Jpeg);
imgRes.ContentId = "imgA";
imgRes.ContentType.Name = "imgA.jpg";
imgRes.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imgRes);
msg.AlternateViews.Add(htmlView);
//sending prepared email
SmtpClient smtp = new SmtpClient();//It reads the SMPT params from Web.config
smtp.Send(msg);
and these are key parts of the html template:
<p>Username: <%USERNAME%></p>
<img src="cid:imgA"/>
I'd like a custom and beautiful mail.
I know that can use html tag in mail.Body but is it good way? What is
the best way ?
I don't know exactly what is that supposed to mean, but generally, there are two ways to do it. (If we talking about images or sources in email etc..)
You can use LinkedResource class of .NET Framework.
Represents an embedded external resource in an email attachment, such
as an image in an HTML attachment.
Alternatively, and more simply in my opinion, if you want to use some images in your email, put the image in a public location then just reference that location in the HTML of the email.

How to send multi-part MIME messages in c#?

I want to send multi-part MIME messages with an HTML component plus a plain text component for people whose email clients can't handle HTML. The System.Net.Mail.MailMessage class doesn't appear to support this. How do you do it?
D'oh, this is really simple... but I'll leave the answer here for anyone who, like me, came looking on SO for the answer before Googling... :)
Credit to this article.
Use AlternateViews, like so:
//create the mail message
var mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me#mycompany.com");
mail.To.Add("you#yourcompany.com");
//set the content
mail.Subject = "This is an email";
//first we create the Plain Text part
var plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
var htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
//send the message
var smtp = new SmtpClient("127.0.0.1"); //specify the mail server address
smtp.Send(mail);

Send url with querystring with SmtpClient

Basic question here: I'm sending emails using the default SmtpClient of the .NET framework (3.5). The bodytype is HTML (IsBodyHtml = true) In the body I've added a url with two parameters in the querystring like so:
http://server.com/page.aspx?var1=foo&var2=bar
This get's encoded to:
http://server.com/page.aspx?var1=foo%26var2=bar (the ampersand is encoded as percent-26)
When doing a simple Request["var2"] I get 'null'.
What should I do to properly encode the ampersand in the mail message?
This works fine for me:
var client = new SmtpClient();
client.Host = "smtp.somehost.com";
var message = new MailMessage();
message.From = new MailAddress("from#example.com");
message.To.Add(new MailAddress("to#example.com"));
message.IsBodyHtml = true;
message.Subject = "test";
string url = HttpUtility.HtmlEncode("http://server.com/page.aspx?var1=foo&var2=bar");
message.Body = "<html><body>Test</body></html>";
client.Send(message);
Use the UrlEncode method. This will do all the encoding of your input string for you.

Categories

Resources