send List<> values with Body in mail - SMTP server - c#

I have to send mail through SMTP server. I can able to send it with single values. But, I want to send List<> values as message body in table format or some other structure. I include my code following :
MailMessage mailObj = new MailMessage("abc#gmail.com", "xyz#gmail.com", "Reg : send mail",
"Emp Name :" + "Emp1" + Environment.NewLine + "Date From : " + Mon + "Date To : " + Fri);
SmtpClient SMTPServer = new SmtpClient("smtp.gmail.com", ***);
SMTPServer.Host = "smtp.gmail.com";
SMTPServer.EnableSsl = true;
SMTPServer.Timeout = 200000;
SMTPServer.Credentials = new System.Net.NetworkCredential("asd#gmail.com", "******");
SMTPServer.Send(mailObj);
I have my list of values as follows :
List<TimesheetValues> mailBody = new SampleDAO().GetDataForMail(dt1, satDate);
How can I include this List<> values with body and send?
I try with following :
List<TimesheetValues> Msg = new List<TimesheetValues>(); string strMsg = ""; int n=1;
foreach(var item in mailBody)
{
strMsg = strMsg + "<table><tr><td>" + n + "</td><td>" + item.Project_Name + "</td><td>" + item.Task_Name + "</td><td>" + item.Notes + "</td><td>" + item.Hrs_Worked + "</td></tr></table>";
n++;
}
strMsg = strMsg + "</br>";
MailMessage mailObj = new MailMessage("abc123#gmail.com", "xyz123#gmail.com", "Reg : Timesheet",
"Emp Name :" + "Emp1" + Environment.NewLine + "Date From : " + Mon + "Date To : " + Fri);
mailObj.Body = "Emp Name : " + "Emp1" + Environment.NewLine + "Date From : " + Date2 + " Date To : " + Date6 + Environment.NewLine + strMsg;
Now I get all records but i have tr td tags with in records and not display as a table. How can i acheive this ?
can anyone help to overcome this..
Thanks in advance...

If you want to read the string into a list again, serialize is better.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(yourList);
mailObj.Body = json;
You can also deserialize in the other side:
List<string> g = JsonConvert.DeserializeObject<List<string>>(body);

I try with this following :
string strMsg = ""
strMsg = timsheetMail + " <table style=\"border-collapse:collapse; text-align:center;\" border=\"1\"><tr><td> Date </td><td> Working Hours </td><td> Task </td><td>Comments</td></tr>";
List<TimesheetValues> Msg = new List<TimesheetValues>(); int n=1;
foreach(var item in mailBody)
{
timesheetData = new TimesheetDetailModel();
timesheetData.Task_Id = matrix.Task_Id;
timesheetData.Hours = matrix.Hours;
//timesheetData.Date = matrix.Date.Date;
timesheetData.Date = matrix.Date.AddDays(1);
timesheetData.EmpId = Convert.ToInt32(Session["EmpId"].ToString());
timesheetData.Notes = matrix.Notes;
strMsg = strMsg+ " <tr><td> " + timesheetData.Date.ToString("dd/MM/yyyy") + "</td><td>" + timesheetData.Hours + "</td><td>" + task + "</td><td>" + timesheetData.Notes + "</td></tr>";
n++;
}
strMsg = strMsg + "</table>";
Its working good now..

Related

Add pause to Alexa without using SSML

Is there a way to add a pause (preferably 1 second) in Amazon Alexa without using SSML? Perhaps there is a trick I can do with the Outputspeech.Text and I just don't know it.
Below, I am saying "Here are works of art by {artist name}" but the name and the start of the works of art become mixed together - in spite of the period - so I end up with things like "Here are the works of art by Pablo Picasso Harlequin..."
I am using C# and my own https endpoint, not AWS Lambda.
Any suggestions? Otherwise I will add it as SSML. Thanks.
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("here are works of art for " + m_artist + ". ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available.";
}
else
{
m_location = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location + ".\n"); // It is located on the " + dr["CurrentLocation"].ToString());
}
sql_conn_data.Close();
response.Response.OutputSpeech.Text = output.ToString();
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
UPDATE
OK. Ended up going the SSML route which looks like this:
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_location_card;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("<speak>");
output.Append("here are works of art for " + m_artist + ". <break time='1s'/> ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available. <break time='1s' />";
m_location_card = "The location is not available. ";
}
else
{
m_location = "It is located on the " + m_current_location + "<break time = '1s' />";
m_location_card = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location_card + ". \n");
}
output.Append("</speak>");
sql_conn_data.Close();
response.Response.OutputSpeech.Ssml = output.ToString();
response.Response.OutputSpeech.Type = "SSML";
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
}
There is not a way to introduce a pause in Alexa without SSML. You will need to build the ssml string and return it back to Alexa using the pause, or the cadence strings.

Property or indexer "Attachments" cannot be assigned to -- it is read only

I´m trying to send mail with image attachment, but it still throwing error
(*Property or indexer "Attachments" cannot be assigned to -- it is read only *)
string pathToPic = #"c:\MyDir\Img\img"+ automaticalyGeneratedNumber.toString() + ".png";
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = Environment.MachineName,
Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
Attachments = new Attachment(#"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(#"c:\MyDir\Img") - 1).ToString() + ".png"),
})
{
smtp.Send(message);
}
Why complicate the code like that. You need to use message.Attachments.Add since the Attachments property is read-only :
var message = new MailMessage(fromAddress, toAddress)
{
Subject = Environment.MachineName,
Body = "PC NAME : " + Environment.MachineName + "\r\nIP ADRESS : " + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1],
};
message.Attachments.Add(new Attachment(#"c:\MyDir\Img" + "/img" + (Saving.CountImagesTaken(#"c:\MyDir\Img") - 1).ToString() + ".png"));
using (message)
{
smtp.Send(message);
}

C#.NET send email based on two conditions

I have the following code segment that sends an email to users based on 'RequestApproval' being set to true on their records in a SQL table - it works perfectly.
SmtpClient mySmtpClient = new SmtpClient();
List<SigList> LST_SigList = LK_CRFData.SigLists.Where(x => x.RequestApproval == true).ToList();
string URL = sponsorURL + OB_CRF.id;
foreach (SigList OB_SigList in LST_SigList)
{
string Name = OB_SigList.UserName.Trim();
Name = Name.Substring(0, Name.IndexOf("."));
Name = Name[0].ToString().ToUpper() + Name.Substring(1, Name.Length - 1);
MailMessage myMessage = new MailMessage("SponsorApproved#nhs.net", OB_SigList.EmailAddress);
myMessage.Subject = "Sponsor has approved the request on the " + TB_DateTimeofImplementationStart.Text.Substring(0, 10) + " for \"" + TB_CNNO.Text + " " + TB_Title.Text + "\"";
myMessage.Body = "Dear " + Name + ", \n\nThe sponsor has now approved CN NO : " + TB_CNNO.Text + "\nTitle : " + TB_Title.Text + "\nImplementation Date : " + TB_DateTimeofImplementationStart.Text.Substring(0, 10) + "\n\nClick the link to open the document:\n" + URL;
mySmtpClient.Send(myMessage);
}
However, for certain functions, I want to send the email where 'Request approval is set to True OR False. I've ammended it to the following to no avail:
List<SigList> LST_SigList = LK_CRFData.SigLists.Where(x => x.RequestApproval == true || x.RequestApproval == false).ToList();
It still sends emails out the old way -only to those who have Request Approval' set to true.
Any ideas?
Thanks

How to resolve newline character when sending an email using SMTP

string strTheBody = #"First Name: " + tbFirst.Text + "\nLast Name: " + tbLast.Text + "\nAddress 1: " + tbAdd1.Text + "\nAddress 2: " + tbAdd2.Text + "";
strTheBody += #"\nCity: " + tbCity.Text + "\nState: " + ddlTechState.SelectedValue + "\nZip Code: " + tbZip.Text + "\nDOB: " + tbDOB.Text + "\nEmail Address: " + tbEmail.Text + "";
strTheBody += #"\nLast Doctor visited: " + ddlTechProvider.SelectedValue + "\nIssue: " + ddlTechIssues.SelectedValue + "\n\nComments: " + HttpUtility.HtmlEncode(tbComments.Text) + "";
MailMessage mmSendEmail = new MailMessage();
mmSendEmail.To.Add("myemail#myweb.com");
mmSendEmail.From = new MailAddress(tbEmail.Text);
mmSendEmail.Subject = "Contacting about " + ddlTechIssues.SelectedValue;
mmSendEmail.Body = strTheBody;
SmtpClient scSend = new SmtpClient("mysmtp.myisp.com");
scSend.Send(mmSendEmail);
Sends the email like this:
First Name: first
Last Name: last
Address 1: my address 1
Address 2: \nCity: some city
State: NV
Zip Code: 90320
DOB: 08/08/2013
Email Address: myemail#email.com\nLast Doctor visited: 0
Issue: Result
Comments: This is a comment
How can I resolve the issue with the \n being displayed if the value is empty and when there is an email address.
# symbol means to read that string literally, and don't interpret
control characters
https://stackoverflow.com/a/3312007/3087342
I suggest using StringBuilder instead, will remove these type of errors and makes your code generally a lot more readable - in terms of formatting the email anyway.

C# form Close message box on button click

Is there a way to get the message box to close and return to the form without it emailing the data?
halfway there atm just need a help with the second if/else if statement. I'm very new to all this.
my code is below :)
//Button
private void submitButton_Click(object sender, EventArgs e)
{
string software = null;
string hardware = null;
foreach (string s in softwareNeededCheckedListBox.CheckedItems)
{
software = software + '\n' + s;
}
foreach (string s in hardwareNeededCheckedListBox.CheckedItems)
{
hardware = hardware + '\n' + s;
}
if (yesRadioButton.Checked == true)
{
yesRadioButton.Text = "Yes";
noRadioButton.Text = " ";
}
if (noRadioButton.Checked == true)
{
noRadioButton.Text = "No";
yesRadioButton.Text = " ";
}
if (MessageBox.Show("First name: " + firstNameTextBox.Text + " " + "Last name: " + lastNameTextBox.Text + "\n" + "\n" +
"Will be working in " + areaOfTheCompanyComboBox.SelectedItem + "\n" + "\n" +
"They will need the following software:" + software + "\n" + "\n" +
"They will need the following hardware:" + hardware + "\n" + "\n" +
"They will be seated: " + seatingLocationRichTextBox.Text + "\n" + "\n" +
"Any further Comments: " + notesRichTextBox.Text + "\n" + "\n" +
"Do they require a phone: " + noRadioButton.Text + yesRadioButton.Text + "\n" + "\n" +
"Date they start: " + completionDateTimePicker.Text + "\n" + "\n" +
"Are you happy with the information shown above?" + "\n" + "\n" +
MessageBoxButtons.OKCancel) == DialogResult.OK)
{
MailMessage mail = new MailMessage();
SmtpClient smtpserver = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("xxxxx#gmail.com");
mail.To.Add("xxxxx#xxxxxx.co.uk");
mail.Subject = "Test Mail";
mail.Body = "First name: " + firstNameTextBox.Text + " " + "Last name: " + lastNameTextBox.Text + "\n" + "\n" +
"Will be working in " + areaOfTheCompanyComboBox.SelectedItem + "\n" + "\n" +
"They will need the following software:" + software + "\n" + "\n" +
"They will need the following hardware:" + hardware + "\n" + "\n" +
"They will be seated: " + seatingLocationRichTextBox.Text + "\n" + "\n" +
"Any further Comments: " + notesRichTextBox.Text + "\n" + "\n" +
"Do they require a phone: " + noRadioButton.Text + yesRadioButton.Text + "\n" + "\n" +
"Date they start: " + completionDateTimePicker.Text;
smtpserver.Port = 587;
smtpserver.Credentials = new System.Net.NetworkCredential("**", "********");
smtpserver.Send(mail);
MessageBox.Show("Your Form has been sent ");
}
You actually forgot you place commas to your MessageBox.Show to have the correct arguments/parameters.
if (MessageBox.Show("Body of your message box",
"Title Of Your MessageBox",
MessageBoxButtons.OKCancel,
MessageBoxIcon.Information) == DialogResult.OK)
{
}
That will only e-mail if the user clicks OK. You can handle the cancel button by using DialogResult.Cancel
I would personally put the MessageBox in a dialogResult variable. For instance:
var dialogResult = MessageBox.Show("FIrst name .... ");
Then you can check if the user pressed OK or Cancel
if (dialogResult == DialogResult.OK) {
// Send the e-mail
} else if (dialogResult == DialogResult.Cancel) {
// Do what you need to do / return to the form.
}
To show a messagebox with OK and Cancel you need:
MessageBox.Show(this, "Message", "Title", MessageBoxButtons.OKCancel);

Categories