email send from database and date format in email C#

Kevin Fitzgerald 1 Reputation point
2022-03-15T02:18:36.573+00:00

Hi, I am trying to figure out coding on email send dynamically from database table in there (see this mail.To.Add("Kevin.Fitzgerald@Stuff .com"); and I don't want my email but any user's email dynamically from database table (see the table "ManageLicenses.PocEmail") . Also the date format came out incorrectly. see the code and image.`

![using System;  
using System.Collections.Generic;  
using System.Configuration;  
using System.Data;  
using System.Data.SqlClient;  
using System.Diagnostics;  
using System.IO;  
using System.Linq;  
using System.Net.Mail;  
using System.Text;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
  
namespace WebApplication3  
{  
    public partial class WebForm2 : System.Web.UI.Page  
    {  
        String strcon = ConfigurationManager.ConnectionStrings["LicenseMngConnectionString"].ConnectionString;  
        protected void Page_Load(object sender, EventArgs e)  
        {  
  
            if (!Page.IsPostBack)  
            {  
                binddata();  
  
            }  
        }  
  
        public void binddata()  
        {  
            SqlConnection con = new SqlConnection(strcon);  
            try  
            {  
                con.Open();  
                string str = "Select ManageLicenses.Id, ManageLicenses.PocEmail, ManageLicenses.ExpiratioDate, ManageLicenses.SendEmailToPoc from ManageLicenses";  
                DataSet set = new DataSet();  
                SqlCommand cmd = new SqlCommand(str, con);  
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);  
                sqlDataAdapter.Fill(set);  
                gv.DataSource = set.Tables[0];  
                gv.DataBind();  
  
            }  
            catch (Exception ex)  
            {  
  
            }  
            finally  
            {  
                con.Close();  
            }  
  
  
  
  
        }  
  
        protected void sendgvdata_Click(object sender, EventArgs e)  
        {  
  
            sendmail();  
            Response.Write("success");  
        }  
  
  
  
        public void sendmail()  
        {  
            DateTime ExpiratioDate;  
            //string sTime = System.DateTime.Now.AddDays(2).ToString("dd MMM yyyy") & " " &  
            //   System.DateTime.Now().ToShortTimeString & " +0100";  
  
            DateTime.TryParse(gv.SelectedRow.Cells[3].Text, out ExpiratioDate);  
            DateTime currentdate = DateTime.Now;  
            string ExpirationDateforemail = ExpiratioDate.ToString("MM/dd/yyyy");  
            int daysLeft = Convert.ToInt32((ExpiratioDate - currentdate).TotalDays);  
                          
            string emailtext = string.Format("License will expire on " + ExpirationDateforemail + " and only have {1} days left.", ExpirationDateforemail, daysLeft);  
  
             
              
            MailMessage mail = new MailMessage();  
  
            mail.From = new MailAddress("******@gmail.com");  
            mail.To.Add("******@gmail.com");  
            mail.Subject = "Send Email To POC";  
            mail.Body += EmailMessage.Text;  
            mail.Body += "<br/>";  
            mail.Body += "<br/>";  
            mail.Body += emailtext;  
            mail.Body += "<br/>";  
            mail.Body += "<br/>";  
            mail.Body += "<html><body></body></html>";  
            mail.IsBodyHtml = true;  
            mail.Body += "<br/>";  
            SmtpClient smtp = new SmtpClient("01AESVC-MBA.dodig.mil", 25);  
            smtp.EnableSsl = true;  
            smtp.Send(mail);  
  
        }  
  
        public string getgvdata(GridView gv)  
        {  
            StringBuilder strBuilder = new StringBuilder();  
            StringWriter strWriter = new StringWriter(strBuilder);  
            HtmlTextWriter htw = new HtmlTextWriter(strWriter);  
            gv.RenderControl(htw);  
            return strBuilder.ToString();  
        }  
        public override void VerifyRenderingInServerForm(Control control)  
        {  
            /* Verifies that the control is rendered */  
        }  
    }  
}][1]  
Developer technologies ASP.NET Other
Developer technologies C#
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2022-03-15T08:38:43.493+00:00

    Try

    DateTime.TryParse( gv.SelectedRow.Cells[2].Text, out ExpiratioDate )

    and

    mail.To.Add( gv.SelectedRow.Cells[1].Text ).


  2. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2022-03-15T10:04:43.517+00:00

    Hi @Kevin Fitzgerald ,
    Regarding the date format, you can directly set the data type to date, and then use it directly in the code.

    string licesenname = "licesenname";  
                string str1 = GridView1.SelectedRow.Cells[3].Text;      
                DateTime currentdate = DateTime.Now;  
                int daysLeft =Convert.ToInt32( (DateTime.Parse(str1) - currentdate).TotalDays);  
                string emailtext = string.Format("{0} will expire on {1} and only have {2} days left", licesenname,str1, daysLeft);  
                Response.Write(emailtext);  
    

    183281-1.jpg
    For dynamically sent emails you can try the following code:

               string A = GridView1.SelectedRow.Cells[2].Text;  
                mail.To.Add(A);  
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  3. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-03-15T12:11:19.327+00:00

    For days left.

    public class DateHelper  
    {  
        /// <summary>  
        /// Format date as days left  
        /// </summary>  
        /// <param name="expiryDate">Expiration date</param>  
        /// <returns>days remaining</returns>  
        public static string CalculateExpirationTime(DateTime expiryDate)  
        {  
            var currentDate = DateTime.Now;  
            var dateDifference = (expiryDate - currentDate);  
            return dateDifference.Days >= 1 ? $"{ dateDifference.Days } day(s)" : "Expired";  
        }  
    }  
    

    Then use it, formatting is up to you.

    DateTime expirationDate = new (2022, 3, 21);  
    var emailtext = $"License will expire on {expirationDate:MM/dd/yyyy} and only have {DateHelper.CalculateExpirationTime(expirationDate)} days left.";  
    

    In regards to the actual email body, you might consider storing the email body in a database table with replacement tokens which you use String.Replace to setup at runtime.

    183292-figure1.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.