使用SMTP协议发送邮件

时间:2023-03-09 03:52:30
使用SMTP协议发送邮件
class Program
{
static void Main(string[] args)
{
if (args != null && args.Length > )
{
try
{
inputmodel obj = new inputmodel(args);
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Host = obj.SmtpHost;//如使用163的SMTP服务器发送邮件:"smtp.163.com";
client.UseDefaultCredentials = true;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.Credentials = new System.Net.NetworkCredential(obj.FromMail, obj.FromPwd);//账号、密码(用授权码比较安全)
client.Port = ; System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
Message.From = new System.Net.Mail.MailAddress(obj.FromMail);
foreach (var p in obj.ToMail.Split(','))
{
Message.To.Add(p);//收件人
Console.WriteLine(p);
}
Message.Subject = obj.Subject;//主题
Message.Body = obj.Body;//内容
Message.SubjectEncoding = System.Text.Encoding.UTF8;//主题编码
Message.BodyEncoding = System.Text.Encoding.UTF8;//内容编码
Message.Priority = System.Net.Mail.MailPriority.High;//邮件级别
Message.IsBodyHtml = true;
client.Send(Message);
Console.WriteLine("发送成功");
}
catch (Exception e)
{
Console.WriteLine($"error:{e.Message}");
} }
else
{
Console.WriteLine("必要参数如下:");
Console.WriteLine("-f FromMail");
Console.WriteLine("-t ToMail");
Console.WriteLine("-s Subject");
Console.WriteLine("-b Body");
Console.WriteLine("-h SmtpHost");
Console.WriteLine("-p FromPwd");
}
} private class inputmodel
{
public inputmodel(string[] args)
{
int i = -;
i = Array.FindIndex(args, o => o == "-f");
if (i != -)
{
this.FromMail = args[i + ];
}
i = Array.FindIndex(args, o => o == "-t");
if (i != -)
{
this.ToMail = args[i + ];
}
i = Array.FindIndex(args, o => o == "-s");
if (i != -)
{
this.Subject = args[i + ];
}
i = Array.FindIndex(args, o => o == "-b");
if (i != -)
{
this.Body = args[i + ];
}
i = Array.FindIndex(args, o => o == "-h");
if (i != -)
{
this.SmtpHost = args[i + ];
}
i = Array.FindIndex(args, o => o == "-p");
if (i != -)
{
this.FromPwd = args[i + ];
}
}
public string FromMail { get; set; }
public string ToMail { get; set; }
public string Body { get; set; }
public string Subject { get; set; }
public string FromPwd { get; set; }
public string SmtpHost { get; set; }
}
}