본문 바로가기

프로그래밍/C#

C#으로 이메일 보내기

구성 파일을 생성한 다음 포트, SMTP 서버, 이메일, 암호를 추가해야 합니다.

Windows 양식에서 이메일 텍스트 상자, 제목 텍스트 상자, 메시지 텍스트 상자만 있으면 됩니다.

<코드>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public Task SendEmailAsync(string email, string subject, string htmlMessage)
{
var credentials = new NetworkCredential(_configuration.GetValue<string>("Smtp:UserName"), _configuration.GetValue<string>("Smtpassword"));
var mail = new MailMessage()
{
From = new MailAddress(_configuration.GetValue<string>("Smtp:UserName")),
Subject = subject,
Body = htmlMessage,
};
mail.IsBodyHtml = true;
mail.To.Add(new MailAddress(email));
using var client = new SmtpClient()
{
Port = 587,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = _configuration.GetValue<string>("Smtp:Server"),
EnableSsl = true,
Credentials = credentials
};
return client.SendMailAsync(mail);
}
cs