아래 코드 참조.
지메일 셋팅 하고, 파일 첨부해서 '비동기' 방식으로 보내기.
(주석처리된 send 는 동기 방식)
한글을 사용하기 위해 제목(subject), 내용(body) 의 인코딩을 UTF8로 셋팅해준다.
- using System;
- using System.Windows.Forms;
- using System.Net.Mail;
- namespace EmailTestApplication
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- try
- {
- MailMessage mail = new MailMessage();
- SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
- //set the address
- mail.From = new MailAddress("your g-mail address");
- mail.To.Add("target e-mail address");
- //set the contents
- mail.Subject = "Subject Test Mail";
- mail.Body = "This is for testing SMTP mail from GMAIL";
- mail.BodyEncoding = System.Text.Encoding.UTF8;
- mail.SubjectEncoding = System.Text.Encoding.UTF8;
- //set attachment
- System.Net.Mail.Attachment attachment;
- attachment = new System.Net.Mail.Attachment("D:\\temp\\file.txt");
- mail.Attachments.Add(attachment);
- //setting smtpServer
- SmtpServer.Port = 587;
- SmtpServer.Credentials = new System.Net.NetworkCredential("your_ID", "your_password");
- SmtpServer.EnableSsl = true;
- //SmtpServer.Send(mail);
- // MessageBox.Show("mail Send");
- //async send mail
- object userState = mail;
- SmtpServer.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
- SmtpServer.SendAsync(mail, userState);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
- void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
- {
- //Get the Original MailMessage object
- MailMessage mail = (MailMessage)e.UserState;
- //write out the subject
- string subject = mail.Subject;
- if (e.Error == null)
- {
- // Send succeeded
- string message = string.Format("Send Mail with subject [{0}]", subject);
- MessageBox.Show(message);
- }
- else if (e.Cancelled == true)
- {
- string message = string.Format("Send canceld for mail with subject [{0}]", subject);
- MessageBox.Show(message);
- }
- else
- {
- // log exception
- string message = string.Format("Send Mail Fail - Error: [{0}]", e.Error.ToString());
- MessageBox.Show(message);
- }
- }
- }
- }
'Dev > C#' 카테고리의 다른 글
[C#,SQL] SqlDatareader 로 Float 데이터 가져오기 (0) | 2012.11.22 |
---|---|
[C#] 윈도우 사용자 계정 가져오기 (0) | 2012.10.17 |
[C#] 문자열에 특정 문자열 포함 여부 확인하는 방법 (0) | 2012.10.17 |
[C#] double 을 이용한 Ceiling 오류 처리 (0) | 2012.06.19 |
[C#] 정적 메소드(Static Method)와 인스턴스 메소드(Instance Method) 차이 (0) | 2012.03.23 |