In this example/demo, i will explain how to send an email from your ASP.Net website or C# application using your GMail account but it can be easily be modified to use other email accounts.
If you want to use a different email account then you need the following checklist:
-
Port number - This is usually "25" but can be different as some block this port to prevent spam which i know we all hate!
-
SMTP host address - usually "smtp.YourEmailDomain.com" but this can also be different
-
SSL - Is ssl needed? if yes then make sure the property is set to true
-
Email & Password - The email and password of your email account
The code example below has some details hardcoded in for easier viewing but when you add it to your website/application then i would advise to make the details like port/email/password/smtp as parameters.
First make sure you add the following namespace:
using
System.Net.Mail;
public void sendGmail(string
emailTo, string subject, string body)
{
//Creates a new
message and sets the From address
System.Net.Mail.MailMessage
msg = new System.Net.Mail.MailMessage();
msg.From = new
MailAddress("YOUREMAIL@gmail.com",
"Your Name");
// Adds addresses
the To/CC/Bcc fields
msg.To.Add(emailTo);
msg.CC.Add("CCEmailAddress@whatever.com");
msg.Bcc.Add("BccEmailAddress@whatever.com");
//Creates a new
attachement and adds it to the message
Attachment
file = new Attachment("c:/test.txt");
msg.Attachments.Add(file);
// Sets the
subject text and the Encoding
msg.Subject = subject;
msg.SubjectEncoding = System.Text.Encoding.UTF8;
// Sets the body
text and the Encoding
msg.Body = body;
msg.BodyEncoding = System.Text.Encoding.UTF8;
// Sets the mail
to be a HTML message
msg.IsBodyHtml = true;
// Creates a new
SMTP client to send the above message
SmtpClient
client = new SmtpClient();
// Sets the login
credentials for your email account
client.Credentials = new System.Net.NetworkCredential("YOUREMAIL@gmail.com", "YOURPASSWORD");
// Sets the port
number for the Gmail server
client.Port = 587;
// Sets the smtp
server to Gmails
client.Host = "smtp.gmail.com";
// Enables SSL
client.EnableSsl = true;
// This will send
the message based on all the previous details
client.Send(msg);
}
Acronyms
SSL: Secure Sockets Layer
SMTP: Simple Mail Transfer Protocol
c6103f09-e423-48a5-a73a-681c44445459|2|4.0