- Back to Home »
- ASP.Net , C# , SMTP »
Posted by : Jebastin
Saturday, 14 December 2013
C#:
- public bool Send_Email(string Subject, string Body, string ToEmail, string AttachmentUrl)
- {
- bool Sent = false;
- try
- {
- if (!string.IsNullOrEmpty(ToEmail))
- {
- string FromEmail = "", Username = "", Password = "", Host = "", Port = "";
- FromEmail = Convert.ToString(ConfigurationManager.AppSettings["FromEmail"]);
- Username = Convert.ToString(ConfigurationManager.AppSettings["Username"]);
- Password = Convert.ToString(ConfigurationManager.AppSettings["Password"]);
- Host = Convert.ToString(ConfigurationManager.AppSettings["Host"]);
- Port = Convert.ToString(ConfigurationManager.AppSettings["Port"]);
- bool UseSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["UseSsl"]);
- System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
- System.Net.NetworkCredential cred = new System.Net.NetworkCredential(Username, Password);
- if (ToEmail.Contains(','))
- {
- string[] ToEmailArray = ToEmail.Split(',');
- foreach (string si in ToEmailArray)
- {
- mail.To.Add(si);
- }
- }
- else
- {
- mail.To.Add(ToEmail);
- }
- mail.Subject = Subject;
- mail.From = new System.Net.Mail.MailAddress(FromEmail, Convert.ToString(ConfigurationManager.AppSettings["FromName"]));
- mail.IsBodyHtml = true;
- mail.Body = Body;
- if (!string.IsNullOrEmpty(AttachmentUrl))
- {
- System.Net.Mail.Attachment Attachment;
- if (AttachmentUrl.Contains(','))
- {
- string[] AttachmentUrlArray = ToEmail.Split(',');
- foreach (string url in AttachmentUrlArray)
- {
- string strUrl = Uri.EscapeUriString(url);
- if (File.Exists(strUrl))
- {
- Attachment = new System.Net.Mail.Attachment(strUrl);
- mail.Attachments.Add(Attachment);
- }
- }
- }
- else
- {
- string strUrl = Uri.EscapeUriString(AttachmentUrl);
- if (File.Exists(strUrl))
- {
- Attachment = new System.Net.Mail.Attachment(strUrl);
- mail.Attachments.Add(Attachment);
- }
- }
- }
- System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
- smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
- smtp.UseDefaultCredentials = false;
- smtp.EnableSsl = UseSsl;
- smtp.Credentials = cred;
- smtp.Host = Host;
- smtp.Port = Convert.ToInt32(Port);
- smtp.Send(mail);
- Sent = true;
- }
- }
- catch
- {
- Sent = false;
- }
- return Sent;
- }
Configuration in appSettings.config:
- <!-- Email Data Configuration Start -->
- <add key="FromName" value="Company Name or Any Text"/>
- <add key="FromEmail" value="example@gmail.com"/>
- <add key="Username" value="example@gmail.com"/>
- <add key="Password" value="password"/>
- <add key="Host" value="smtp.gmail.com"/>
- <add key="Port" value="587"/>
- <add key="UseSsl" value="true"/>
- <add key="ToEmail" value="example@gmail.com"/>
- <!-- Email Data Configuration End -->