generated from kzi-nastava/dotnet-wpf-starter-template
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #443 from kzi-nastava/refactor/EmailService
[refactor] EmailService
- Loading branch information
Showing
1 changed file
with
36 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,38 +18,47 @@ public static void SendEmail(string toEmail, string subject, string body, PdfDoc | |
{ | ||
try | ||
{ | ||
MailAddress fromAddress = new("[email protected]", "LangLang"); | ||
MailAddress toAddress = new(toEmail); | ||
|
||
MailMessage mail = new(); | ||
mail.From = fromAddress; | ||
mail.To.Add(toAddress); | ||
mail.Subject = subject; | ||
mail.Body = body; | ||
|
||
if (pdf != null) | ||
{ | ||
var attachment = ConvertFromPdf(pdf); | ||
mail.Attachments.Add(attachment); | ||
} | ||
|
||
SmtpClient smtpClient = new SmtpClient | ||
{ | ||
Host = "smtp.gmail.com", | ||
Port = 587, | ||
EnableSsl = true, | ||
Credentials = new NetworkCredential("[email protected]", "lckfqhhpgyespyso") | ||
}; | ||
|
||
MailMessage mail = CreateMailMessage(toEmail, subject, body, pdf); | ||
SmtpClient smtpClient = ConfigureSmtpClient(); | ||
smtpClient.Send(mail); | ||
|
||
} | ||
catch (Exception ex) | ||
{ | ||
throw new SmtpException(ex.Message); | ||
throw new SmtpException("Failed to send email: " + ex.Message, ex); | ||
} | ||
} | ||
|
||
private static MailMessage CreateMailMessage(string toEmail, string subject, string body, PdfDocument? pdf) | ||
{ | ||
MailAddress fromAddress = new("[email protected]", "LangLang"); | ||
MailAddress toAddress = new(toEmail); | ||
|
||
MailMessage mail = new(); | ||
mail.From = fromAddress; | ||
mail.To.Add(toAddress); | ||
mail.Subject = subject; | ||
mail.Body = body; | ||
|
||
if (pdf != null) | ||
{ | ||
var attachment = ConvertFromPdf(pdf); | ||
mail.Attachments.Add(attachment); | ||
} | ||
} | ||
|
||
|
||
return mail; | ||
} | ||
|
||
private static SmtpClient ConfigureSmtpClient() | ||
{ | ||
return new SmtpClient | ||
{ | ||
Host = "smtp.gmail.com", | ||
Port = 587, | ||
EnableSsl = true, | ||
Credentials = new NetworkCredential("[email protected]", "lckfqhhpgyespyso") | ||
}; | ||
} | ||
|
||
private static Attachment ConvertFromPdf(PdfDocument document) | ||
{ | ||
MemoryStream ms = new MemoryStream(); | ||
|