Sending Mail through Asp.Net
Common and important aspect used in Web designing is email sending. Basic use of sending email from a Web page is to enable the users to give their comments/suggestions through web form. The .NET Framework provides extremely straightforward means to send emails. ASP .NET makes use of SmtpMail and MailMessage classes to send an emaill. The SmtpMail and MailMessage classes are defined in the System.Web.Mail namespace. The MailMessage class has properties and methods for creating an email and the SmtpMail class has send method to send an email.
public bool SendingMail(string fromAddress,string toAddress,string subject,string bodymessage,string[] fileattachement)
{
try
{MailAddress mailfrom = new MailAddress(fromAddress);
MailAddress mailto = new MailAddress(toAddress);
MailMessage newmsg = new MailMessage(mailfrom, mailto);
newmsg.Subject = subject;
newmsg.Body = bodymessage;////For File Attachment, more file can also be attached
foreach (var files in fileattachment)
{Attachment att = new Attachment(files);
newmsg.Attachments.Add(att);
}//Configure the smtp Address
SmtpClient smtps = new SmtpClient("smtp.gmail.com", 587);
smtps.UseDefaultCredentials = false;//passing the Network credentials
smtps.Credentials = new NetworkCredential("mail@gmail.com", "pwd");
//passing ssl
smtps.EnableSsl = true;
smtps.Send(newmsg);return true;
}catch (Exception ex)
{return false;
}
}
On Button Click
bool Status = SendingMail(txtfromAddress.Text, txttoAddress.Text, txtsubject.Text, txtbodymessage.Text, files);
if (Status)
lblEmailStatus.Text =
"your mail has been sent successfully";
else
lblEmailStatus.Text = "sorry! your mail not sent successfully";