using MimeKit; using System; using MailKit.Net.Smtp; using MailKit.Security; using MailKit; using MailKit.Security; using System.Net.Mail; namespace EmailServiceApi.Services { public class EmailService { public string SendEmailmethode1(string smtpServer, string fromAddress, string toAddress, string subject, string body,string username,string password) { try { // Create MimeMessage var message = new MimeMessage(); message.From.Add(new MailboxAddress("Sender Name", fromAddress)); message.To.Add(new MailboxAddress("Recipient Name", toAddress)); message.Subject = subject; // Create body part var bodyPart = new TextPart("plain") { Text = body }; // Construct the multipart/mixed container to hold the message text and any attachments var multipart = new Multipart("mixed"); multipart.Add(bodyPart); // Add the multipart/alternative part to the message message.Body = multipart; // Send email using MailKit using (var client = new MailKit.Net.Smtp.SmtpClient()) { client.Connect(smtpServer, 587, SecureSocketOptions.StartTls); // Assuming SMTP server is using port 587 for TLS encryption client.Authenticate(username, password); // Provide credentials here if required by your SMTP server client.Send(message); client.Disconnect(true); } return "Email sent successfully."; } catch (Exception ex) { string errorMessage = "Failed to send email(methode 1): " + ex.Message; // Check if inner exception exists and its message is not null if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message)) { errorMessage += "\n Details: " + ex.InnerException.Message; } throw new Exception(errorMessage); } } public string SendEmailMethode2(string smtpServer, string fromAddress, string toAddress, string subject, string body, int? times = 1) { try { MailMessage oEmail = new MailMessage(fromAddress, toAddress, subject, body); var emailClient2 = new System.Net.Mail.SmtpClient(smtpServer); for (int i = 0; i < times; i++) { oEmail.Subject = subject + " (" + i + ")"; emailClient2.Send(oEmail); //Send email } return "Email sent successfully."; } catch (Exception ex) { string errorMessage = "Failed to send email(methode 2): " + ex.Message; // Check if inner exception exists and its message is not null if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message)) { errorMessage += "\n Details: " + ex.InnerException.Message; } throw new Exception(errorMessage); // return $"Failed to send email: {ex.Message}"; } } } }