两种.NET定时发送邮件代码实例


当前第2页 返回上一页

sendMail方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

public static string sendMail(string mailSubjct, string mailBody, string mailFrom, List<string> mailAddress, string hostIP, string username, string password, bool ssl)

  {

   string str = "";

   try

   {

    MailMessage message = new MailMessage

    {

     IsBodyHtml = true,

     Subject = mailSubjct,

     Body = mailBody,

 

     From = new MailAddress(mailFrom)

    };

    for (int i = ; i < mailAddress.Count; i++)

    {

     message.To.Add(mailAddress[i]);

    }

    SmtpClient client = new SmtpClient

    {

     EnableSsl = ssl,

     UseDefaultCredentials = false

    };

    NetworkCredential credential = new NetworkCredential(username, password);

    client.Credentials = credential;

    client.DeliveryMethod = SmtpDeliveryMethod.Network;

    client.Host = hostIP;

    client.Port = x;

    client.Send(message);

   }

   catch (Exception exception)

   {

    str = exception.Message;

   }

   return str;

  }


第二种方式:

定时发邮件可以用Timer来设置时间,放在了Global.asaxApplication_Start里面

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

using System.Net.Mail;

using System.Timers;

protected void Application_Start(object sender, EventArgs e)

  {

   Timer t = new Timer(60000);//设计时间间隔,如果一个小时执行一次就改为3600000 ,这里一分钟调用一次

   t.Elapsed += new ElapsedEventHandler(t_Elapsed);

   t.AutoReset = true;

   t.Enabled = true;

  }

  private void t_Elapsed(object sender, ElapsedEventArgs e)

  {

   MailMessage message = new MailMessage();

   message.From = Messagefrom;

   message.To.Add(MessageTo);    //收件人邮箱地址可以是多个以实现群发

   message.Subject = MessageSubject;

   message.Body = MessageBody;

   message.IsBodyHtml = true;    //是否为html格式

   message.Priority = MailPriority.High; //发送邮件的优先等级

   SmtpClient sc = new SmtpClient();

   sc.Host = "smtp.sina.com";    //指定发送邮件的服务器地址或IP

   sc.Port = 25;       //指定发送邮件端口

   //sc.UseDefaultCredentials = true;

   //sc.EnableSsl = true;

   sc.Credentials = new System.Net.NetworkCredential(“**@**”, "密码"); //指定登录服务器的用户名和密码

    sc.Send(message);  //发送邮件

  }

到此全部代码就写完了。

创建一个控制台程序,生成一个exe 采用windows的计划任务程序指定每天的某个时间点发送思路就是这个思路比服务简单

以上就是两种.NET定时发送邮件代码实例的详细内容!

返回前面的内容

相关阅读 >>

比较c#中值类型和引用类型的区别

c# 5.0引入了两个关键字 --async和await

c#开发微信门户及应用(二)之微信消息处理和应答的图文代码教程

.net core + angular cli 实现开发环境搭建

比较c#和java中面向对象语法的区别

c#实现表格隔行换色

c# winform跨线程访问控件的图文详解

c#中.net框架的简介

c#如何实现自动更新本地程序的实例分析

c#使用aforge实现摄像头录像功能的案例

更多相关阅读请进入《定时发送邮件》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...