1 public class EmailSender 2 { 3 private string smtpServer; 4 private int smtpPort; 5 private string senderEmail; 6 private string senderPassword; 7 private string subjectPrefix; 8 private string emailContext; 9 10 /// <summary> 11 /// Constructor for EmailSender class. 12 /// </summary> 13 /// <param name="smtpServer">SMTP server address.</param> 14 /// <param name="smtpPort">SMTP server port.</param> 15 /// <param name="senderEmail">Sender's email address.</param> 16 /// <param name="senderPassword">Sender's email password.</param> 17 /// <param name="subjectPrefix">Email subject prefix.</param> 18 /// <param name="emailContext">Email content.</param> 19 public EmailSender(string smtpServer, int smtpPort, string senderEmail, string senderPassword, string subjectPrefix, string emailContext) 20 { 21 this.smtpServer = smtpServer; 22 this.smtpPort = smtpPort; 23 this.senderEmail = senderEmail; 24 this.senderPassword = senderPassword; 25 this.subjectPrefix = subjectPrefix; 26 this.emailContext = emailContext; 27 } 28 29 /// <summary> 30 /// Sends an email. 31 /// </summary> 32 /// <param name="recipientEmail">Recipient's email address.</param> 33 /// <param name="ccEmails">List of CC email addresses.</param> 34 /// <param name="attachmentFilePath">Attachment file path.</param> 35 public void SendMail(string recipientEmail, string[] ccEmails, string attachmentFilePath = "") 36 { 37 try 38 { 39 SmtpClient smtp = new SmtpClient(smtpServer, smtpPort); 40 smtp.DeliveryMethod = SmtpDeliveryMethod.Network; 41 smtp.Credentials = new NetworkCredential(senderEmail, senderPassword); 42 43 MailMessage message = new MailMessage(); 44 message.From = new MailAddress(senderEmail); 45 message.To.Add(new MailAddress(recipientEmail)); 46 message.Subject = $"{subjectPrefix} "; 47 message.Body = $"{emailContext}"; 48 message.BodyEncoding = Encoding.UTF8; 49 message.IsBodyHtml = true; 50 51 if (ccEmails != null && ccEmails.Length > 0) 52 { 53 foreach (string ccEmail in ccEmails) 54 { 55 message.CC.Add(new MailAddress(ccEmail)); 56 } 57 } 58 59 if (File.Exists(attachmentFilePath)) 60 { 61 // Add attachment 62 Attachment attachment = new Attachment(attachmentFilePath, MediaTypeNames.Application.Octet); 63 attachment.ContentDisposition.CreationDate = File.GetCreationTime(attachmentFilePath); 64 attachment.ContentDisposition.ModificationDate = File.GetLastWriteTime(attachmentFilePath); 65 attachment.ContentDisposition.ReadDate = File.GetCreationTime(attachmentFilePath); 66 message.Attachments.Add(attachment); 67 } 68 69 smtp.Send(message); 70 Console.WriteLine("Email sent successfully!"); 71 } 72 catch (Exception ex) 73 { 74 Console.WriteLine(ex.Message); 75 } 76 } 77 }EmailSender
源码地址:https://github.com/yycb1994
标签:封装,string,attachmentFilePath,c#,senderEmail,attachment,new,message,邮件 From: https://www.cnblogs.com/INetIMVC/p/18026885