Introduction:
In this topic, I will explain code to send attachment in email using Gmail in ASP.NET C#.
Description:
Usually, it is necessary to send email to user from ASP.NET application. We should use SMTP (Simple Mail Transfer Protocol) server to send email. If we don't have any SMTP server at that time we can use Gmail SMTP server to send email.
Following is source code to send email in ASP.NET :
In this topic, I will explain code to send attachment in email using Gmail in ASP.NET C#.
Description:
Usually, it is necessary to send email to user from ASP.NET application. We should use SMTP (Simple Mail Transfer Protocol) server to send email. If we don't have any SMTP server at that time we can use Gmail SMTP server to send email.
Following is source code to send email in ASP.NET :
- Import following namespaces :
using System.Net;
using System.Net.Mail;
- Add following button click event with function to send mail :
public bool SendMail(string subject, string body, string to, string attachments)
{
bool result = false;
try
{
string emailSender = "Sender Gmail Email Address";
string passwordSender = "Sender Gmail Password";
using (SmtpClient smtpClient = new SmtpClient())
{
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Credentials = new NetworkCredential(emailSender, passwordSender);
smtpClient.EnableSsl = true;
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress(emailSender);
message.Subject = subject;
message.Body = body;
if (!string.IsNullOrEmpty(attachments))
{
foreach (string attachment in attachments.Split(",".ToCharArray()))
message.Attachments.Add(new Attachment(attachment));
}
message.To.Add(to);
smtpClient.Send(message);
}
}
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}