在send email 前, 先講如何制造email object. 這裡用了一粒class 去包著須要send的內容. 故砌真. object 時, 這個method 可以定義為adapter 的implementation.
private MailMessage createMailMessage(EMAIL email) { MailMessage mail = new MailMessage() { From = new MailAddress(email.FROM_EMAIL_ADDRESS), }; mail.To.Add(new MailAddress(email.TO_EMAIL_ADDRESS)); if (!string.IsNullOrEmpty(email.CC_EMAIL_ADDRESS)) mail.CC.Add(new MailAddress(email.CC_EMAIL_ADDRESS)); if (!string.IsNullOrEmpty(email.BCC_EMAIL_ADDRESS)) mail.Bcc.Add(new MailAddress(email.BCC_EMAIL_ADDRESS)); mail.Subject = email.SUBJECT; mail.Body = email.CONTENT; mail.BodyEncoding = Encoding.UTF8; mail.IsBodyHtml = true; // set priority. switch (email.PRIORITY) { case NotificationPriority.High: mail.Priority = MailPriority.High; break; case NotificationPriority.Normal: mail.Priority = MailPriority.Normal; break; case NotificationPriority.Low: mail.Priority = MailPriority.Low; break; } // Add attachment. if ((email.EMAIL_ATTACHMENT != null) && (email.EMAIL_ATTACHMENT.Count > 0)) { foreach (EMAIL_ATTACHMENT emailAttachment in email.EMAIL_ATTACHMENT) { mail.Attachments.Add(new Attachment(emailAttachment.ATTACHMENT_PATH)); } } return mail; }
負責send mail 時, 則用了一個method call, 配合剛才介紹的method.
public bool Send(EMAIL email) { bool result = false; try { using (SmtpClient smtpClient = new SmtpClient(smtpServer, smtpServerPortNo)) { if (enableAuthentication) { smtpClient.UseDefaultCredentials = enableAuthentication; smtpClient.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpUserpassword); } smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = enableSsl; // Create email and set content. smtpClient.Send(this.createMailMessage(email)); } result = true; } catch (Exception ex) { throw(ex); } return result; }
Leave a Reply