Case_accounting/CaseAccounting/CaseAccountingBusinessLogics/BusinessLogics/MailSender.cs

59 lines
2.0 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using CaseAccountingContracts.BindingModels;
namespace CaseAccountingBusinessLogic.BusinessLogics
{
public class MailSender
{
private string mailLogin = string.Empty;
private string mailPassword = string.Empty;
private string smtpClientHost = string.Empty;
private int smtpClientPort;
public MailSender(){}
public void MailConfig(MailConfigBindingModel config)
{
mailLogin = config.MailLogin;
mailPassword = config.MailPassword;
smtpClientHost = config.SmtpClientHost;
smtpClientPort = config.SmtpClientPort;
}
public async void SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(smtpClientHost, smtpClientPort);
try
{
objMailMessage.From = new MailAddress(mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
MemoryStream ms = new(info.File);
objMailMessage.Attachments.Add(new Attachment(ms, "report.pdf", "application/pdf"));
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(mailLogin, mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
}
}