Datatable as mail in C# console application - c#

I am trying to create html from my dataset using the following code
public static string getHtml(DataTable dataSet)
{
try
{
string messageBody = "<font>The following are the records: </font><br><br>";
if (dataSet.Rows.Count == 0)
return messageBody;
string htmlTableStart = "<table style=\"float:left; border-collapse:collapse; text-align:center;\" >";
string htmlTableEnd = "</table>";
string htmlHeaderRowStart = "<tr style =\"background-color:#6FA1D2; color:#ffffff;\">";
string htmlHeaderRowEnd = "</tr>";
string htmlTrStart = "<tr style =\"color:#555555;\">";
string htmlTrEnd = "</tr>";
string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">";
string htmlTdEnd = "</td>";
foreach (DataColumn dc in dataSet.Columns)
{
messageBody += htmlTableStart;
messageBody += htmlHeaderRowStart;
messageBody += htmlTdStart + dc + htmlTdEnd;
messageBody += htmlHeaderRowEnd;
foreach (DataRow Row in dataSet.Rows)
{
messageBody = messageBody + htmlTrStart;
messageBody = messageBody + htmlTdStart + Row["" + dc + ""] + htmlTdEnd;
messageBody = messageBody + htmlTrEnd;
}
}
messageBody = messageBody + htmlTableEnd;
return messageBody;
}
catch (Exception ex)
{
return null;
}
}
I want to render in a way that
All different tables should come in horizontally. I tried float:left but when i use this html to be send in mail , float-left don't work
Can something be changed in code so that Tables come in hozizontally as

I completed my answer . here is the solution to convert dataset to html
public static string DataTableToHTML(DataTable dataSet)
{
mLogger.Error("DataTableToHTML -------> Start");
try
{
string messageBody = "<font>Following corporate actions are not updated in Security Master: </font><br><br>";
if (dataSet.Rows.Count == 0)
return messageBody;
string htmlTableStart = "<table style=\"border-collapse:collapse; text-align:center;\" >";
string htmlTableEnd = "</table>";
string htmlHeaderRowStart = "<tr style =\"background-color:#6FA1D2; color:#ffffff;\">";
string htmlHeaderRowEnd = "</tr>";
string htmlTrStart = "<tr style =\"color:#555555;\">";
string htmlTrEnd = "</tr>";
string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">";
string htmlTdEnd = "</td>";
messageBody += htmlTableStart;
messageBody += htmlHeaderRowStart;
foreach (DataColumn dc in dataSet.Columns)
{
messageBody += htmlTdStart + dc + htmlTdEnd;
} messageBody += htmlHeaderRowEnd;
foreach (DataRow dr in dataSet.Rows)
{
messageBody = messageBody + htmlTrStart;
foreach (DataColumn dc in dataSet.Columns)
{
messageBody = messageBody + htmlTdStart + dr["" + dc + ""] + htmlTdEnd;
}
messageBody = messageBody + htmlTrEnd;
}
messageBody = messageBody + htmlTableEnd;
mLogger.Error("DataTableToHTML -------> End");
return messageBody;
}
catch (Exception ex)
{
mLogger.Error("Exception in DatatableToHTML" + ex);
return null;
}
}

Related

Encoding missing from reading file

Hello i'm developing a little application that download attachment from unread mails by imap and make a sevarla job on this attachment. Problem is encoding because after i have saved a, for example, txt file, when i load it again letters with accents becomes "?" I dont know why. I tried a several example around on the web (like converting directly the file from ansi to utf-8) with no result. Whe i open a file in windows it works, words are correct.
i have used either ReadAllText that StreamReader in the following example:
string contents = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName, Encoding.UTF8);
using (StreamReader reader = new StreamReader(contents, Encoding.UTF8))
as you can see in the following example if i set directly a string with an accent word, it works, from file no.
Please help me!
check image
Reproducible Code:
using CsvHelper;
using NLog;
using System;
using System.Data;
using System.IO;
using System.Text;
namespace ConsoleApp1
{
class Class1
{
public static void test2()
{
using (var client = new ImapClient())
{
try
{
int porta = Convert.ToInt32(par.portaimap);
bool ssl = Convert.ToBoolean(par.sslimap);
client.Connect(par.host, porta, ssl);
Logger.Info("Connessione server posta riuscita");
}
catch (Exception ex)
{
Logger.Error("Connessione non riuscita; di seguito l'errore: " + ex.Message);
}
try
{
Logger.Info("Autenticazione in corso");
client.Authenticate(par.usernameimap, par.passwordimap);
}
catch (Exception ex)
{
Logger.Error("Connessione non riuscita; di seguito l'errore: " + ex.Message);
}
// The Inbox folder is always available on all IMAP servers...
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadWrite);
Console.WriteLine("Total messages: {0}", inbox.Count);
Console.WriteLine("Recent messages: {0}", inbox.Recent);
var query = SearchQuery.NotSeen;//SearchQuery.SubjectContains("MimeKit").Or(SearchQuery.SubjectContains("MailKit"));
var uids = client.Inbox.Search(query);
var items = client.Inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
Logger.Info("Selezione lista di email non lette");
foreach (var summary in items)
{
var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\", summary.UniqueId.ToString());
// create the directory
Directory.CreateDirectory(directory);
if (summary.Body is BodyPartMultipart)
Logger.Info("Download allegati in corso.");
foreach (var attachment in summary.Attachments)
{
var entity = client.Inbox.GetBodyPart(summary.UniqueId, attachment);
var part = (MimePart)entity;
// note: it's possible for this to be null, but most will specify a filename
var fileName = part.FileName;
var path = Path.Combine(directory, fileName);
try
{
using (var stream = File.Create(path))
part.Content.DecodeTo(stream);
Logger.Info("Allegato scaricato.");
}
catch (Exception ex)
{
Logger.Error("Allegato non scaricato. Di seguito errore: " + ex.Message);
}
int scelta = 0;
string contents = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName, Encoding.UTF8);
Console.WriteLine(contents);
Console.ReadLine();
contents = "Proprietà";
Console.WriteLine(contents);
Console.ReadLine();
string ext = Path.GetExtension(fileName);
SmtpSettings smtpSettings = new SmtpSettings();
smtpSettings.SenderName = "Test";
smtpSettings.server = "smtp.gmail.com";
smtpSettings.Port = 587;
smtpSettings.SenderMail = par.usernameimap;
smtpSettings.Username = par.usernameimap;
smtpSettings.Password = par.passwordimap;
smtpSettings.ToMail1Name = "Test1";
smtpSettings.ToMail1 = "test1#gmail.com";
smtpSettings.ToMail2Name = "Test2";
smtpSettings.ToMail2 = "Test2#bsolution.org";
string PATHTODELETE = "";
if (ext == ".txt")
{
string line1 = File.ReadLines(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName).First();
if (line1 == "FOR|CLIEN|STAB|INSEGNA|INDIRIZZO|CAP|LUOGO|PROV|ORDINE|POS|STATO|DTORD|ORAORD|MALFUNZIONE|COD_RIS|RISORSA|TERMID|ESESIA|STABSIA|ABI|TELEFONO|NOTE|COD_HOST|ACCESSORIO|DESC_HOST|MOD_COLLEG|FUNZ. AGG:|REFERENTE|DT_SCADENZA|LAKA|")
{
DataTable dt;
using (StreamReader reader = new StreamReader(contents, Encoding.UTF8))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.Delimiter = "|";
// Do any configuration to `CsvReader` before creating CsvDataReader.
using (var dr = new CsvDataReader(csv))
{
dt = new DataTable();
dt.Load(dr);
reader.Close();
}
}
//Costruzione body mail csv
string value = "";
string filename = "";
string Msg = "";
foreach (DataRow drow in dt.Rows)
{
value = "";
value += "FOR: " + drow["FOR"].ToString() + "\n";
value += "CLIEN: " + drow["CLIEN"].ToString() + "\n";
value += "STAB: " + drow["STAB"].ToString() + "\n";
value += "INSEGNA: " + drow["INSEGNA"].ToString() + "\n";
value += "INDIRIZZO: " + drow["INDIRIZZO"].ToString() + "\n";
value += "LUOGO: " + drow["LUOGO"].ToString() + "\n";
value += "ORDINE: " + drow["ORDINE"].ToString() + "\n";
value += "POS: " + drow["POS"].ToString() + "\n";
value += "STATO: " + drow["STATO"].ToString() + "\n";
value += "DTORD: " + drow["DTORD"].ToString() + "\n";
value += "ORAORD: " + drow["ORAORD"].ToString() + "\n";
value += "MALFUNZIONE: " + drow["MALFUNZIONE"].ToString() + "\n";
value += "COD_RIS: " + drow["COD_RIS"].ToString() + "\n";
value += "RISORSA: " + drow["RISORSA"].ToString() + "\n";
value += "TERMID: " + drow["TERMID"].ToString() + "\n";
value += "ESESIA: " + drow["ESESIA"].ToString() + "\n";
value += "STABSIA: " + drow["STABSIA"].ToString() + "\n";
value += "ABI: " + drow["ABI"].ToString() + "\n";
value += "TELEFONO: " + drow["TELEFONO"].ToString() + "\n";
value += "NOTE: " + drow["NOTE"].ToString() + "\n";
value += "COD_HOST: " + drow["COD_HOST"].ToString() + "\n";
value += "ACCESSORIO: " + drow["ACCESSORIO"].ToString() + "\n";
value += "DESC_HOST: " + drow["DESC_HOST"].ToString() + "\n";
value += "MOD_COLLEG: " + drow["MOD_COLLEG"].ToString() + "\n";
value += "FUNZ. AGG: " + drow["FUNZ. AGG:"].ToString() + "\n";
value += "REFERENTE: " + drow["REFERENTE"].ToString() + "\n";
value += "DT_SCADENZA: " + drow["DT_SCADENZA"].ToString() + "\n";
value += "LAKA: " + drow["LAKA"].ToString();
Msg = value;
// Save File to .txt
filename = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + DateTime.Now.Millisecond.ToString() + ".txt";
PATHTODELETE = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\";
using (FileStream fParameter = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
StreamWriter m_WriterParameter = new StreamWriter(fParameter);
m_WriterParameter.BaseStream.Seek(0, SeekOrigin.End);
m_WriterParameter.Write(Msg, Encoding.UTF8);
m_WriterParameter.Flush();
m_WriterParameter.Close();
}
smtpSettings.Subject = "Oggetto Temporaneo da cambiare";
Invio(smtpSettings, Msg, filename);
try
{
inbox.AddFlags(summary.UniqueId, MessageFlags.Seen, true);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
}
Logger.Info("Pulizia directory allegati in corso...");
DeleteDirectory(PATHTODELETE);
Logger.Info("Pulizia directory allegati terminata.");
}
else
{
string[] stringSeparators = new string[] { "************************************************************************************************************" };
string[] attivita = contents.Split(stringSeparators, StringSplitOptions.None);
foreach (string att in attivita)
{
Console.WriteLine(att);
string Msg = att;
// Save File to .txt
string filename = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + DateTime.Now.Millisecond.ToString() + ".txt";
PATHTODELETE = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\";
FileStream fParameter = new FileStream(filename, FileMode.Create, FileAccess.Write);
StreamWriter m_WriterParameter = new StreamWriter(fParameter);
m_WriterParameter.BaseStream.Seek(0, SeekOrigin.End);
m_WriterParameter.Write(Msg);
m_WriterParameter.Flush();
m_WriterParameter.Close();
smtpSettings.Subject = "Oggetto Temporaneo da cambiare";
if (att.Contains("OGGETTO"))
{
Invio(smtpSettings, att, filename);
}
else { }
}
Logger.Info("Pulizia directory allegati in corso...");
DeleteDirectory(PATHTODELETE);
try
{
inbox.AddFlags(summary.UniqueId, MessageFlags.Seen, true);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
Logger.Info("Pulizia directory allegati terminata.");
}
}
else
{
}
}
}
}
}
}
}
After searching around on the web i found a solution, here microsoft msdn
Streamreader and maybe readalltext doesn't support accent letters with UTF-8 Encoding, so changing it in UTF-7, letters are showed correctly.
Thank you for all support!

Email Works fine but got two emails at same time?

I try to send email, below code works fine but email sends twice at a time. I tried a lot but I don't know where I made a mistake.
RTElapsedTime.cs:
public void Elapsed()
{
T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);
T1.Interval = 60000;
T1.Enabled = true;
}
public void T1_Elapsed(object source, ElapsedEventArgs e)
{
try
{
MatchingTime = DateTime.Now.ToString("HH:mm");
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
DataTable dt = EmailMgr.EmailServiceScheduleTimeIntervalRunTime(MatchingTime.ToString());
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count : " + dt.Rows.Count);
foreach (DataRow r in dt.Rows)
{
T1.Enabled = false;
RTEmailManagement(r);
T1.Enabled = true;
}
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Tasks are completed.");
}
catch (Exception ex)
{
TraceImplogs.TraceLTService(ex.Message);
}
}
DataTable dataRPT1 = new DataTable();
public DataTable ReportGeneration2(EmailDTO EETO)
{
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
dataRPT1 = EmailMgr.EmailLatearrivalReport(EETO.Departments, "0", EETO.ReportType);
return dataRPT1;
}
public void RTEmailManagement(DataRow dr)
{
EDTO = null;
EDTO = new EmailDTO();
MatchingTime = DateTime.Now.ToString("HH:mm");
EDTO.SecondTime = MatchingTime;
EDTO.ScheduleTime = dr["rshtime"].ToString();
EDTO.ToEmails = dr["rsh_altrntmail"].ToString();
EDTO.CcEmails = dr["rsh_ccmail"].ToString().Split(';');
EDTO.Subject = dr["rsh_subjct"].ToString();
EDTO.ReportID = dr["reportid"].ToString();
EDTO.Departments = dr["rsh_dept"].ToString();
EDTO.ReportType = Convert.ToInt32(dr["rsh_typly"].ToString());
EDTO.weekly = dr["rsh_day"].ToString();
EDTO.Monthly = dr["rsh_dayofmnth"].ToString();
EDTO.Day = dr["xday"].ToString();
EDTO.Body = dr["rsh_body"].ToString();
EDTO.langcode = Convert.ToInt32(dr["langcode"].ToString());
CompanyID = Int32.Parse(dr["Company_id"].ToString());
dataRPT1 = ReportGeneration2(EDTO);
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count---- : " + dataRPT1.Rows.Count);
foreach (DataRow r in dataRPT1.Rows)
{
EDTO.CcEmails = new List<string>(EDTO.CcEmails) { r["Manager"].ToString() }.ToArray();
EDTO.CcEmails = EDTO.CcEmails.Distinct().ToArray();
//EDTO.CcEmails[EDTO.CcEmails.Length-1] = dataRPT1.Rows[k]["Manager"].ToString();
EDTO.ToEmails1 = r["email_addr"].ToString();
EDTO.LateArrival = r["LateArrivals"].ToString();
if (EDTO.ScheduleTime == EDTO.SecondTime)
{
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "time matched");
switch (Convert.ToInt32(EDTO.ReportType))
{
case 0:
case 1:
EmailConfiguration(CompanyID, EDTO);
break;
case 2:
//TraceImplogs.TraceLTService("tyoe 2 new");
EmailConfiguration(CompanyID, EDTO);
break;
case 3:
// TraceImplogs.TraceLTService("tyoe 3 new");
EmailConfiguration(CompanyID, EDTO);
break;
default:
break;
}
}
}
// else TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "not matching");
}
public void EmailConfiguration(int compid, EmailDTO EDTO)
{
try
{
ConfigDTO mlDTO = new ConfigDTO();
EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
DataTable EmailConfigDT = EmailMgr.SelectAllCompanyEmailConfiguration(compid);
RTMailProcessing Mprocess = new RTMailProcessing();
mlDTO.ConfigMail = EmailConfigDT.Rows[0]["comp_email"].ToString();
mlDTO.ConfigPwd = EmailConfigDT.Rows[0]["comp_pwd"].ToString();
mlDTO.ConfigHost = EmailConfigDT.Rows[0]["host_name"].ToString();
mlDTO.ConfigPort = Convert.ToInt32(EmailConfigDT.Rows[0]["host_port"].ToString());
Mprocess.EmailProcessing(mlDTO, EDTO);
}
catch (Exception ex)
{
TraceImplogs.TraceLTService(ex.Message + " Email Error");
}
}
Email processing cs code.
RtMailprocessing.cs:
public void EmailProcessing(ConfigDTO conDTO, EmailDTO EDTO)
{
RTMsg.language(EDTO.langcode);
conDTO.ConfigPwd = utility.Decrypt_Secure_Keylock(conDTO.ConfigPwd);
// TraceImplogs.TraceLTService("Entered Config file" + conDTO.ConfigPwd);
SmtpClient smtp = new SmtpClient
{
Host = conDTO.ConfigHost,
Port = conDTO.ConfigPort,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(conDTO.ConfigMail, conDTO.ConfigPwd)
// Timeout = 30000,
};
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
// TraceImplogs.TraceLTService("Entered inside");
if (EDTO.ToEmails != "")
{
using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(conDTO.ConfigMail, EDTO.ToEmails1, EDTO.Subject, EDTO.Body))
{
for (int k = 0; k < EDTO.CcEmails.Length; k++)
{
if (EDTO.CcEmails[k] != "")
{
message.CC.Add(EDTO.CcEmails[k].TrimEnd(';'));
}
else
{
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Ccmails are empty");
}
}
message.CC.Add(EDTO.ToEmails);
message.Subject = ""; message.Body = "";
message.Subject = EDTO.Subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
// ReportGeneration(EDTO);
string EmailBody = "";
if (attach != null)
{
message.Attachments.Add(attach);
string[] RepBody = EDTO.Body.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
/*****with attachment***/
foreach (string lines in RepBody)
{
EmailBody += "<p style='font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #333333; margin-left: 10px'>" + lines + "</p>";
}
message.Body = "Email Testing";
message.BodyEncoding = System.Text.Encoding.UTF8;
//message.Attachments.Dispose();
//message.Dispose();
}
if (dataRPT.Rows.Count < 1)
{
message.Body ="Test Email";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Attachments.Clear();
}
message.IsBodyHtml = true; //Send this as plain-text
smtp.Send(message);
TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + NameRPT + " sent successfully.");
message.CC.Clear();
//((IDisposable)smtp).Dispose();
//message.Attachments.Dispose();
//message.Dispose();
}
}
}
When I debug with breakpoint loop run single time only but I got two email. I don't know where I made exactly mistake.
Thanks in advance.
I'm going to take a guess, you're not unsubscribing the event:
T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);
You need to unsubscribe it:
T1.Elapsed -= new ElapsedEventHandler(T1_Elapsed);
The email server processed both messages and delivered them at the same time.

HTML Formatted Emails not displayed in gmail

When Im trying to generate HTML Formatted Result set and sending the resultset as Email using SMTPsettings,Its working fine in Outlook but the same htmlformat is not displayed in gmail It displays as a plain Text.
public void GenerateRpt()
{
DataSet ds= new DataSet();
//Result set is assigned to the dataset object.
if ds[0].Rows.Count == 0)
return;
else
{
try
{
StringBuilder builder = new StringBuilder();
builder.Append("<html xmlns='http://www.w3.org/1999/xhtml'>");
builder.Append("<head>");
builder.Append("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />");
builder.Append(" <style type='text/css'> #page {} table { border-collapse: collapse;border-spacing: 0;empty-cells: show} ");
builder.Append(" .Default { font-family: Calibri;background-color: transparent;border-style: none;vertical-align: bottom;margin-left: 0in;");
builder.Append(" writing-mode: page;color: #000000;font-size: 11pt; font-style: normal;text-shadow: none; text-decoration: none ! important;font-weight: normal;}");
builder.Append(" .ce2 { background-color: #95b3d7;border-width: 0.0349cm;border-style: solid;border-color: #000000;color: #000000;font-size: 11pt;");
builder.Append("font-style: normal;font-weight: bold;margin-left: 0in;text-shadow: none;font-family: Calibri;text-decoration: none ! important;");
builder.Append("vertical-align: middle;writing-mode: page;text-align: center ! important;}");
builder.Append(" .ce5 { background-color: transparent;border-width: 0.0349cm;border-style: solid;border-color: #000000;color: #000000;font-size: 11pt;");
builder.Append("font-style: normal;font-weight: normal;margin-left: 0in;text-shadow: none;font-family: Calibri;text-decoration: none ! important;");
builder.Append("vertical-align: middle;writing-mode: page;text-align: center ! important;}");
builder.Append(" .ce6 { background-color: #a6a6a6;border-width: 0.0349cm;border-style: solid;border-color: #000000;color: #000000;font-size: 11pt;");
builder.Append("font-style: normal;font-weight: bold;margin-left: 0in;text-shadow: none;font-family: Calibri;text-decoration: none ! important;");
builder.Append("vertical-align: middle;writing-mode: page;text-align: center ! important;}");
builder.Append(" .ce13 { background-color: transparent;border-width: 0.0349cm;border-style: solid;border-color: #000000;color: #000000;font-size: 11pt;");
builder.Append("font-style: normal;font-weight: normal;margin-left: 0in;text-shadow: none;font-family: Calibri;text-decoration: none ! important;");
builder.Append("vertical-align: bottom;writing-mode: page;}");
builder.Append(" .contentText {font-size: 11pt;font-weight: normal;font-style: normal;font-style: Calibri;font-weight: bold;COLOR: #cccccc;");
builder.Append("</style>");
builder.Append("</head>");
builder.Append("<body>");
builder.Append("<table border='0' cellpadding='1' cellspacing='1' width='70%'> ");
builder.Append("<tr class='ro1'><td colspan='4'><b><p>RPT NAME</p></b></td></tr>");
builder.Append("<tr class='ro1'>");
builder.Append("<td class='ce2'><p>COL1</p></td>");
builder.Append("<td class='ce2'><p>COL2</p></td>");
builder.Append("<td class='ce2'><p>COL3</p></td>");
builder.Append("<td class='ce2'><p>COL4</p></td>");
builder.Append("</tr>");
string tempdrow = string.Empty;
int i;
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
builder.Append("<td class='ce5'>");
builder.Append("<p>" + ds.Tables[0].Rows[i]["Col1"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i]["Col2"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i]["Col3"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i]["Col4"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("</tr>");
}
// When No more records in the Dataset show the Grand Total.
builder.Append("<tr class='ro2'>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<b><p>GRAND TOTAL </p></b>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i - 1]["Col2"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i - 1]["Col3"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i - 1]["Col4"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("</tr>");
builder.Append("</table>");
string sVehRejsubject = System.Configuration.ConfigurationManager.AppSettings["Subject"].ToString();
sendmail(builder.ToString(), sVehRejsubject);
}
catch (Exception ex)
{
ex.Message();
}
}
}
// Mail Sending Part
void sendmail(string strResultSet,string strRptType)
{
try
{
if (strResultSet.ToString() != "")
{
string strMessage1 = string.Empty, TestEmp = "Mani";
strMessage1 = strResultSet.ToString();
strMessage1 += "<br><br><font color='blue'><b>Date:</b></font> " + DateTime.Now.ToString("dd/MM/yyyy") + "<BR>";
strMessage1 += "<br>Regards,<BR><BR>";
strMessage1 += TestEmp + "</b><br>";
<BR></td></tr></table></body></html>";
MailMessage mail = new MailMessage();
//SMTP SETTINGS DEFINED IN APP.CONFIG FILE
System.Net.Mail.SmtpClient _client = new System.Net.Mail.SmtpClient();
string sFrom = System.Configuration.ConfigurationManager.AppSettings["emailFrom"].ToString();
string sTo = System.Configuration.ConfigurationManager.AppSettings["emailTo"].ToString();
string sCC = System.Configuration.ConfigurationManager.AppSettings["emailCC"].ToString();
string sBCC = System.Configuration.ConfigurationManager.AppSettings["emailBCC"].ToString();
string sDisplayName = System.Configuration.ConfigurationManager.AppSettings["emailFromDisplayName"].ToString();
mail.From = new MailAddress(sFrom, sDisplayName);
mail.To.Add(new MailAddress(sTo));
if (sCC.ToString() != "")
{
mail.CC.Add(sCC);
}
if (sBCC.ToString() != "")
{
mail.Bcc.Add(sBCC);
}
mail.IsBodyHtml = true;
mail.Subject = strRptType + " AS ON - " + System.DateTime.Now.ToString("dd/MM/yyyy");
mail.Body = strMessage1;
_client.Send(mail);
}
}
catch (Exception ex)
{
Ex.Message();
return;
}
}
Email providers, does not allow the entire spectrum of html tags to be included in a message. In case you try to include an unsupported tag it will be ignored or automatically changed to another tag.
It is the same with unsupported css attributes.
For example <br/> is not allowed and will be ignored
What you should do is use universally supported Html tags only.
I've found this page which lists the universally supported html tags and css attributes
Good luck !

When mail is triggered getting blank fields in mail

Below is the code for sending mail.Iam not getting any error or exception but when mail is triggered iam getting blank fields for region name,location name and partner code. Partner name also is displayed.
if (objUser.UserMasterId == 0)
{
objUser.FunctionalityId = 10; //Partner Creation
dtPartnerMailDetails = UserMasterBL.GetPartnerMailDetails(objUser);
if (dtPartnerMailDetails.Rows.Count > 0)
{
objUser.RegionName = dtPartnerMailDetails.Rows[0]["RegionName"].ToString();
objUser.LocationName = dtPartnerMailDetails.Rows[0]["LocationName"].ToString();
objUser.PartnerCode = dtPartnerMailDetails.Rows[0]["PartnerCode"].ToString();
objUser.PartnerName = dtPartnerMailDetails.Rows[0]["partnername"].ToString();
}
dtMailDetails = UserMasterBL.GetMailDetails(objUser);
if (dtMailDetails.Rows.Count > 0)
{
string strMailFROM = "WiproIMSCertificationPortal#wipro.com";
string ToMailIds = dtMailDetails.Rows[0]["ToMailIds"].ToString();
string CCMailIds = dtMailDetails.Rows[0]["CCMailIds"].ToString();
/* string Region = dtPartnerMailDetails.Rows[0]["regionname"].ToString();
string Location = dtPartnerMailDetails.Rows[0]["locationname"].ToString();
string PartnerCode = dtPartnerMailDetails.Rows[0]["PartnerCode"].ToString();
string partnername = dtPartnerMailDetails.Rows[0]["partnername"].ToString();*/
string Region = objUser.RegionName;
string Location = objUser.LocationName;
string PartnerCode = objUser.PartnerCode;
string PartnerName = objUser.PartnerName;
//string partnercodeauto = objUser.PartnerCodeid;
string strmailBody = "<html><body><font face='Verdana' size=2 color=#0E6192>";
strmailBody += "Dear Administrator " + "<br/><br/>";
strmailBody += "Kindly approve below request, Created by " + objUser.PartnerName + "<br/> <br/>";
strmailBody += "<br/><br/>";
strmailBody += "<table border=1><tr><td><b>sl no </b></td><td><b>Region</b></td><td><b>Location</b></td><td><b>Partner Name</b></td><td><b>Partner Code</b></td>";
strmailBody += "<tr><td>1 </td><td>" + Region + "</td><td> " + Location + " </td><td>" + PartnerName + " </td><td>" + PartnerCode + " </td></tr></table>";
strmailBody += "<br/><br/>";
strmailBody += "</body></html>";
strmailBody += "Best Regards" + "<br/>" + " IMS Team";
strmailBody += "<br/><br/>";
strmailBody += "Disclaimer: This is a system generated mail. Please do not reply to this mail. For any queries, Please log a call in https://serviceconnect.wipro.com <br/>";
string strMailSubject = "Partner Addition " + objUser.PartnerCode + "";
Helper.Sendmail(strMailFROM, ToMailIds, strMailSubject, strmailBody, CCMailIds, null, null);
}
Data layer code:
public static DataTable GetPartnerMailDetails(UserMasterOL objUser)
{
if (objUser == null)
{
throw new ArgumentNullException("objUser");
}
DataTable dtGetPartnerMailDetails = new DataTable();
dtGetPartnerMailDetails.Locale = CultureInfo.InvariantCulture;
try
{
DbCommand DbCmd = DataAccessbase.Database.GetStoredProcCommand(Constants.GetPartnerCreationMailDetails);
DataAccessbase.Database.AddInParameter(DbCmd, "#PartnerCode", DbType.String, objUser.PartnerCode);
dtGetPartnerMailDetails = DataAccessbase.Database.ExecuteDataSet(DbCmd).Tables[0];
}
stored procedure:
ALTER PROCEDURE [dbo].[GetPartnerCreationMailDetails]
(
#PartnerCode INT
)
AS
BEGIN
SET NOCOUNT ON
select rm.regionname,pm.PartnerCode,pm.partnername,lm.locationname from partnermaster pm
inner join regionmaster rm on
rm.regionid=pm.regionid
inner join locationmaster lm on
lm.locationid=pm.locationid
where pm.PartnerCode=#PartnerCode
end
Try closing the TR on this line:
strmailBody += "<table border=1><tr><td><b>sl no </b></td><td><b>Region</b></td><td><b>Location</b></td><td><b>Partner Name</b></td><td><b>Partner Code</b></td>";
It should be
strmailBody += "<table border=1><tr><td><b>sl no </b></td><td><b>Region</b></td><td><b>Location</b></td><td><b>Partner Name</b></td><td><b>Partner Code</b></td></tr>";

inserting data into database for different object type at the same time?

Here is my code. I am trying to insert data by using this MyResponses(). This is my next click event.
nextclick event
{
Section surveySection = DataAccess.AccessSurveySectionByParameters(currentSurvey.EmplID, currentSurvey.UnitId, currentSurvey.SurveyId, currentSurvey.Sort.ToString(), NextStep, GetSurveyResponses());
PopulateSurveySection(currentSurvey, surveySection);
}
private string MyResponses()
{
string resp = "";
foreach (Control ctr in pnlSurveySection.Controls)
{
if (ctr is Table)
{
Table tbl = ctr as Table;
foreach (TableRow tr in tbl.Rows)
{
string sres = "";
string currid = tr.Cells[0].Attributes["ID"];
TableCell tc = tr.Cells[1];
if(currid.StartsWith("editable"))
{
currid.Substring(0, 14);
foreach (Control ctrc in tc.Controls)
{
if (ctrc is TextBox)
{
sres = currid + "||" + (ctrc as TextBox).Text.Trim();
}
else if (ctrc is RadioButtonList)
{
sres = currid + "||" + (ctrc as RadioButtonList).SelectedValue;
}
else if (ctrc is DropDownList)
{
sres = currid + "||" + (ctrc as DropDownList).SelectedValue;
}
else if (ctrc is CheckBoxList)
{
sres = currid + "||" + (ctrc as CheckBoxList).SelectedItem.ToString() + "|";
}
}
}
resp = resp + (string.IsNullOrEmpty(resp) ? "|||" : "") + sres;
}
}
It is not inserting data. and not giving me any error..Any suggestion appreciate
Thanks

Categories