如何使用基于动态计划时间的Windows服务发送邮件

时间:2019-06-27 04:48:42

标签: c# asp.net windows-services

我已经创建了Windows服务来发送邮件,并且工作正常,它正在Onstart()方法上发送电子邮件,但是我想在特定时间发送电子邮件,例如我拥有每个用户的数据来发送电子邮件在指定的时间。

我已经创建了Windows服务,用于通过OnStart()方法发送电子邮件。

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Data.SqlClient;

namespace EmailSmsService
{
    public partial class Service1 : ServiceBase
    {

        Timer timer = new Timer(); // name space(using System.Timers;)
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            List<Appointments> appointments = GetAppointments();
            foreach (var val in appointments)
            {
                SendAppointmentEmail(val.Email, val.SenderEmail, val.SenderEmailPassword);
            }
            WriteToFile("Service is started at " + DateTime.Now);
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 5000; //number in milisecinds
            timer.Enabled = true;
        }

        public void SendAppointmentEmail(string Receiver, string SenderEmail, string SenderEmailPassword)
        {
            if (SenderEmail == "")
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("example@gmail.com");
                mail.To.Add(Receiver);
                mail.Subject = "Appointment Reminder";
                mail.Body = "Dear Sir/Mam,  <br /> Welcome to WHS";
                mail.IsBodyHtml = true;
                SmtpServer.Port = 587;
                SmtpServer.Credentials = new NetworkCredential("example@gmail.com", "nefzvlsehx");
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);

            }
            else
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress(SenderEmail);
                mail.To.Add(Receiver);
                mail.Subject = "Appointment Reminder";
                mail.Body = "Dear Sir/Mam,  <br /> Welcome";
                mail.IsBodyHtml = true;
                SmtpServer.Port = 587;
                SmtpServer.Credentials = new NetworkCredential(SenderEmail, SenderEmailPassword);
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);

            }
        }

        protected override void OnStop()
        {
            WriteToFile("Service is stopped at " + DateTime.Now);
        }

        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            WriteToFile("Service is recall at " + DateTime.Now);
        }

        public void WriteToFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to. 
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }



        public List<Appointments> GetAppointments()
        {
            try
            {
                //System.Diagnostics.Debugger.Launch();
                List<Appointments> appointments = new List<Appointments>();
                using (SqlConnection myConnection = new SqlConnection("Data Source=xxxxxxx;Initial Catalog=xxx;User ID=xxx;Password=xxxxx;"))
                {
                    string oString = "select ca.ScheduleStartDate,c.Email,os.AppointmentReminderBeforeDays,os.AppointmentReminderBeforeHours,os.AppointmentMissedNotificationAfterHours,os.AppointmentReminderTime,os.SenderEmail,os.SenderEmailPassword from ClientAppointment ca join Client c on c.Id = ca.ClientId join Organization org on org.Id = ca.OrganizationId join OrganizationSetting os on os.OrganizationId = org.Id";
                    SqlCommand oCmd = new SqlCommand(oString, myConnection);
                    myConnection.Open();
                    using (SqlDataReader oReader = oCmd.ExecuteReader())
                    {
                        while (oReader.Read())
                        {
                            var val = new Appointments();
                            val.ScheduleStartDate = Convert.ToDateTime(oReader["ScheduleStartDate"]);
                            val.Email = oReader["Email"].ToString();
                            var beforedays = oReader["AppointmentReminderBeforeDays"];
                            var beforehours = oReader["AppointmentReminderBeforeHours"];
                            var afterhours = oReader["AppointmentMissedNotificationAfterHours"];
                            if (!(beforedays is DBNull))
                            {
                                val.AppointmentReminderBeforeDays = Convert.ToInt32(beforedays);
                            }
                            else
                            {
                                val.AppointmentReminderBeforeDays = null;
                            }
                            if (!(beforehours is DBNull))
                            {
                                val.AppointmentReminderBeforeHours = Convert.ToInt32(beforehours);
                            }
                            else
                            {
                                val.AppointmentReminderBeforeHours = null;
                            }
                            if (!(afterhours is DBNull))
                            {
                                val.AppointmentMissedNotificationAfterHours = Convert.ToInt32(afterhours);
                            }
                            else
                            {
                                val.AppointmentMissedNotificationAfterHours = null;
                            }
                            //val.AppointmentReminderBeforeHours = Convert.ToInt32(oReader["AppointmentReminderBeforeHours"]);
                            //val.AppointmentMissedNotificationAfterHours = Convert.ToInt32(oReader["AppointmentMissedNotificationAfterHours"]);
                            val.AppointmentReminderTime = oReader["AppointmentReminderTime"].ToString();
                            val.SenderEmailPassword = oReader["SenderEmailPassword"].ToString();
                            val.SenderEmail = oReader["SenderEmail"].ToString();
                            appointments.Add(val);
                        }

                        myConnection.Close();
                    }
                }

                return appointments;
            }
            catch (Exception e)
            {
                WriteToFile("Service Failed At " + DateTime.Now + "Due To This" + e);
                return null;
            }
        }

        public class Appointments
        {
            public DateTime? ScheduleStartDate { get; set; }
            public string Email { get; set; }
            public int? AppointmentReminderBeforeDays { get; set; }
            public int? AppointmentReminderBeforeHours { get; set; }
            public int? AppointmentMissedNotificationAfterHours { get; set; }
            public string AppointmentReminderTime { get; set; }
            public string SenderEmail { get; set; }
            public string SenderEmailPassword { get; set; }
        }

    }
}

0 个答案:

没有答案