C#

C# gmail 전송방법 SMTP

Stater 2019. 3. 27. 23:28

C#과 Gmail을 사용한 SMTP 메일 전송방법 

 

- gmail의 ID,PW 필요.

 

1) 단일 사용자에게 보낼 때 아래의 소스 코드를 사용하면 gmail을 통한 메일 전송이 가능하다.


string BalSinID = "발신인 이메일주소";  //ex)computer@gmail.com
string SuSinID = "수신인이메일주소";   //ex)computer@naver.com
string BalSinPW = "비밀번호";            //발신인의 비밀번호
string BalSinSubject = "발신제목";      //발신 메일 제목
string BalSinContent = "발신내용";     //발신 메일 내용
string SMTP_MAIL_CONIG = "smtp.gmail.com"; //smtp.gmail.com  smtp.SMTP명.com
int SMTP_MAIL_CONIG_PORT = 587;//연결포트 //smtp 연결포트
System.Net.Mail.Attachment Attachement;//첨부파일 메일
MailMessage msg = new MailMessage(BalSinID, SuSinID, BalSinSubject, BalSinContent);
Attachement = new System.Net.Mail.Attachment("C:\\Desktop\\logo.gif");
msg.Attachments.Add(Attachement);

msg.IsBodyHtml = true; //HTML 메일 전송인경우 true 설정
SmtpClient smtp = new SmtpClient(SMTP_MAIL_CONIG, SMTP_MAIL_CONIG_PORT);
smtp.EnableSsl = true;

smtp.Credentials = new NetworkCredential(BalSinID, BalSinPW);

smtp.Send(msg);
Console.WriteLine("메일전송이 완료되었습니다.");

 

2) 다중 사용자에게 보낼경우 아래의 소스코드를 사용하면 gmail을 통한 메일 전송이 가능하다.

 

모든 부분은 위의 소스코드와 동일하지만 SuSinID 부분만 객체를 배열로 표현하여 "1","2","3"이 부분에

"철수@naver.com","영희@naver.com","나고야@naver.com" 식으로 입력후 실행해주면 다중으로 전송된다.

 

string BalSinID = "발신자 메일주소";
            string[] SuSinID = { "1","2","3"}; 
            string BalSinPW = "비밀번호";
            string BalSinSubject = "단체테스트메일";
            string BalSinContent = "안녕하세요 테스트입니다.";
            string SMTP_MAIL_CONIG = "smtp.gmail.com";
            int SMTP_MAIL_CONIG_PORT = 587;//연결포트
            System.Net.Mail.Attachment Attachement;
            for (int i=0;i<SuSinID.Length;i++) { 
            MailMessage msg = new MailMessage(BalSinID, SuSinID[i], BalSinSubject, BalSinContent);
            //Attachement = new System.Net.Mail.Attachment("C:\\Desktop\\logo.gif");
            //msg.Attachments.Add(Attachement);

            msg.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient(SMTP_MAIL_CONIG, SMTP_MAIL_CONIG_PORT);
            smtp.EnableSsl = true;

            smtp.Credentials = new NetworkCredential(BalSinID, BalSinPW);

            smtp.Send(msg);
             for(int j = 1; j < SuSinID.Length+1; j++) { 
            Console.WriteLine(j+"번째 이메일 전송이 완료되었습니다.");
                }

 

배운기능:

1) gmail을 통한 메일 전송기능

2) SMTP사용법

3) 파일 첨부하여 이메일 전송하는 방법

반응형

'C#' 카테고리의 다른 글

ASP.NET 보안  (0) 2019.05.08
ASP.NET 보안  (0) 2019.05.07
C# Task 주저리주저리  (0) 2019.04.22