Skip to main content
 首页 » 编程设计

c#之csharp schedule 电子邮件 razor mvc4

2024年02月13日37mayingbao

我可以在 php/mysql 中轻松地做到这一点,但是,c# mvc razor 是一个完全不同的故事。

我想做的就是在服务器上设置一个 cron 作业(我认为这不是 c# mvc 的 cron 作业,甚至不知道它叫什么),以便可以根据月份发送电子邮件:1mth , 2 个月等

下面是我的 sendEmail,它不起作用,因为我需要在代码中包含用户名/密码才能工作,在我看来这是荒谬的(“php”中的 sendemail 不需要发件人凭据)除非有更好的方法,否则请告诉我方法。

//send email 
public void sendEmail() 
        { 
            MailMessage message = new MailMessage(); 
            message.From = new MailAddress("toemail@domain.com"); 
            message.To.Add(new MailAddress("toemail@domain.com")); 
            message.Subject = "This is my subject"; 
            message.Body = "testing testing testing"; 
            SmtpClient client = new SmtpClient(); 
            client.Host = "localhost"; 
            client.UseDefaultCredentials = false; 
            client.Send(message); 
        } 
 
//date difference 
public decimal monthDifference(DateTime d1, DateTime d2) 
        { 
            if (d1 > d2) 
            { 
                DateTime hold = d1; 
                d1 = d2; 
                d2 = hold; 
            } 
 
            decimal monthsApart = Math.Abs((12 * (d1.Year - d2.Year)) + d2.Month - d1.Month - 1); 
            decimal daysinStartingMonth = DateTime.DaysInMonth(d1.Year, d1.Month); 
            monthsApart = monthsApart + (1 - ((d1.Day - 1) / daysinStartingMonth)); 
 
            decimal daysinEndingMonth = DateTime.DaysInMonth(d2.Year, d2.Month); 
            monthsApart = monthsApart + (d2.Day / daysinEndingMonth); 
            return monthsApart; 
        } 
 
//i will use linq to query the database and get the start and end date 
if(monthDifference(start, end) == 2 || monthDifference(start, end) == 1) 
{ 
sendEmail(); 
} 

请您参考如下方法:

您正在使用 SmtpClient 对象,您猜它使用的是 SMTP。

在 PHP/MySQL 中,您经常使用 sendmail,它能够从服务器发送电子邮件,而不是 SMTP 服务器。

Windows 不包含此功能,您将始终必须使用某种邮件中继提供商来向世界发送电子邮件。

如果您不想存储用户名/密码,请将您的 SMTP 服务器配置为允许来自特定 IP 或主机名的匿名连接。

或者您可以将 SMTP 登录凭据存储在您的 app.config 中。