namespace VECV_WebApi.Models.EmailServices
{
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
public class EmailServices
{
///
/// Function used to send mail.
///
/// Message detail want to send in mail.
/// Mail Receiver
/// Subject of mail
public void SendMail(string message, string mailTo, string subject)
{
try
{
MailModel mail=new MailModel
{
MailTo = ConfigurationManager.AppSettings["SMTP_To"],
Msg = message,
Subject = subject,
IsBodyHtml = true,
SMTP_User = ConfigurationManager.AppSettings["SMTP_User"],
SMTP_From = ConfigurationManager.AppSettings["SMTP_From"],
SMTP_Host = ConfigurationManager.AppSettings["SMTP_Host"],
SMTP_Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTP_Port"]),
SMTP_Pwd = ConfigurationManager.AppSettings["SMTP_Pwd"],
Enable_SSL = Convert.ToBoolean(ConfigurationManager.AppSettings["Enable_SSL"])
};
MailMessage msg = new MailMessage(mail.SMTP_From, mail.MailTo, mail.Subject, mail.Msg);
msg.IsBodyHtml = mail.IsBodyHtml;
if (mail.attach != null)
{
Attachment attach = CreateAttachment(mail.attach);
msg.Attachments.Add(attach);
}
if (!string.IsNullOrEmpty(mail.MaillCC))
msg.CC.Add(mail.MaillCC);
NetworkCredential cred = new
NetworkCredential(mail.SMTP_User, mail.SMTP_Pwd);
SmtpClient mailClient = new SmtpClient(mail.SMTP_Host, mail.SMTP_Port);
mailClient.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["Enable_SSL"]);
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = cred;
mailClient.Send(msg);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
///
/// Function create attachement with the mail.
///
///
///
Attachment CreateAttachment(EncodedAttachment encodedAtt)
{
MemoryStream reader = new MemoryStream(Convert.FromBase64String(encodedAtt.Base64Attachment));
Attachment att = new Attachment(reader, encodedAtt.Name, encodedAtt.MediaType);
return att;
}
}
public class MailModel
{
public string MailTo { get; set; }
public string MaillCC { get; set; }
public string Subject { get; set; }
public string Msg { get; set; }
public bool IsBodyHtml { get; set; }
public EncodedAttachment attach { get; set; }
public string SMTP_From { get; set; }
public string SMTP_User { get; set; }
public string SMTP_Host { get; set; }
public string SMTP_Pwd { get; set; }
public int SMTP_Port { get; set; }
public bool Enable_SSL { get; set; }
}
public class EncodedAttachment
{
public string Base64Attachment;
public string Name;
public string MediaType;
}
}