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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| using System.Net.Mail; using System.Net;
namespace Test { public class SendMail { private SmtpClient _emailClient; public class UserInfo { public string Email { get; set; } public string DisplayName { get; set; } } public string SendMail( string subject, string body, ICollection<UserInfo> tos, ICollection<UserInfo>? ccs = null, ICollection<UserInfo>? bccs = null, ICollection<Attachment>? attachments = null) {
string host = "smtp.qq.com"; int port = 587; bool enableSsl = true; string username = "yourqqemail"; string password = "yourpassword"; string senderAddress = "yourqqemail"; string senderDisplayName = "test";
_emailClient = new SmtpClient { Host = host, Port = port, EnableSsl = enableSsl, Credentials = new NetworkCredential { UserName = username, Password = password } }; MailMessage message = new() { From = new MailAddress(senderAddress, senderDisplayName) };
foreach (UserInfo user in tos) { message.To.Add(new MailAddress(user.Email, user.DisplayName)); } if (ccs != null) { foreach (UserInfo user in ccs) { message.CC.Add(new MailAddress(user.Email, user.DisplayName)); } } if (bccs != null) { foreach (UserInfo user in bccs) { message.Bcc.Add(new MailAddress(user.Email, user.DisplayName)); } } if (attachments != null) { foreach (Attachment attachment in attachments) { message.Attachments.Add(attachment); } } message.Subject = subject; message.Body = body; message.IsBodyHtml = true; message.Priority = MailPriority.Normal;
try { _emailClient.Send(message); return "邮件发送成功"; } catch (Exception ex) { return ex.Message; } } } }
|