最近在做一个监听服务器的小工具,要每隔一个小时登陆,当登陆不上时,要给相关人员发邮件,
其中用到的有c#的两个类一个是SmtpClient,还有一个就是MailMessage,有了这两个类再加以设置就基本完成了邮件功能,这里我使用的是qq邮箱,所以,smtp服务器设为:
smtp.qq.com;如果有用到其他的可以根据情况来修改。我这里不需要添加附件,所以没有写这个,有需求的可以在网上找找,很多人都已经研究过了,再次谨做总结。
下面来晒晒发邮件的功能吧
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using System.Timers;
using System.Xml;
using System.Net;
class Program
{
//-------------------------------------------------------------------------
static SmtpClient smtp_client = setSmtpClient();
//-------------------------------------------------------------------------
static void Main(string[] args)
{
List<string> mToAdress = new List<string>() {"934065124@qq.com"};
Console.WriteLine("-------------------------------------------------------------------------");
string sub = "(这是一封测试邮件)";
string body = "您好,测试机器人于 " + System.DateTime.Now + " 登录时无法登录,请安排工作人员排查服务器故障!";
onSendEMail(smtp_client, "发件人邮箱", mToAdress, sub, body, false);
Console.WriteLine("-------------------------------------------------------------------------");
Console.ReadLine();
}
//-------------------------------------------------------------------------
public static void onSendEMail(SmtpClient smtp_client, string m_sender, List<string> m_receiver, string m_subject, string m_content, bool m_is_html)
{
string sender = m_sender;
string subject = m_subject;
string content = m_content;
bool is_html = m_is_html;
Console.WriteLine("sender : " + m_sender);
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(m_sender);
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
mailMessage.IsBodyHtml = false;
mailMessage.Subject = subject;
mailMessage.Body = content;
mailMessage.IsBodyHtml = is_html;
Console.Write("receiver : ");
foreach (var item in m_receiver)
{
mailMessage.To.Add(item);
Console.Write( item+"; ");
}
try
{
Console.WriteLine();
Console.WriteLine("subject : " + subject);
Console.WriteLine("content : " + content);
//使用异步发送,不会阻塞该线程
smtp_client.SendAsync(mailMessage, mailMessage);
}
catch(Exception ex)
{
mailMessage.Dispose(); //主动释放资源
smtp_client.Dispose();
}
}
//-------------------------------------------------------------------------
public static SmtpClient setSmtpClient()
{
// 设置smtp服务器
SmtpClient smtp_client = new SmtpClient("smtp.qq.com", 25);
smtp_client.UseDefaultCredentials = false;
smtp_client.Credentials = new NetworkCredential("发件人邮箱地址", "发件人邮箱密码");
smtp_client.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp_client.EnableSsl = false;
smtp_client.Timeout = 10000;
return smtp_client;
}
}
运行结果: