Click here to Skip to main content
Click here to Skip to main content

Send Emails in ASP.NET using Gmail Credentials

By , 10 Nov 2008
 

Introduction

As ASP.NET web developers, we often have to include an email sending module in our websites. When I was completing my third year project in the university, I had the same requirement in my web project. I had to go through so many web sites and blogs to find a solution. Using the class file included with this article, you can send emails by entering your Gmail account credentials.

Background

Make sure to instantiate the instance of this class with the correct parameters.

Using the Code

To use this class, add this class to the App_Code folder in your website. Then, create a web page to get the required user input to send a mail. E.g.: To, Subject, and Message. Then, edit the username and password files as you want. Here, to allow a user to send mails, make sure you get the username and password using the website. Then, add two more variables to pass the username and password to the application.

Edit sendMail() as follows:

public static void sendMail(string to, string from, string subject, 
              string body,string username, string password)
{
    ///Smtp config
    SmtpClient client = new SmtpClient("smtp.gmail.com", 465);
    // Edit password and username
    client.Credentials = new NetworkCredential(""+username+"@gmail.com", password);
    client.EnableSsl = true;

    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = 
                ""+username+"@gmail.com";
    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = password;

If you do not allow every user to send email, but only for certain users, then you can use a common email for all the email senders, succh as admin@obrs.com. Then, you don't need to change any other method definition, but make sure to change the username and the password.

client.Credentials = new NetworkCredential("USERNAME@gmil.com", "PASSWORD");
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = 
            "USERNAME@gmail.com";
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "PASSWORD";

Points of Interest

The main feature in this class is it has a back up plan, just in case, to invoke. The mail sending method is sendMail(), but if it fails, it invokes an alternate mail sending method SendMailAlt() using the appropriate attributes.

But, this second method does not allow us to send attachments. So don't allow the user to add attachments to any of the methods.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Harshana Eranga Martin
Engineer Computer Science & Engineering,Uni. Of Moratuwa.
Sri Lanka Sri Lanka
Member
I'm currently an undergraduate in the University of
Moratuwa in the faculty of Engineering and my field of specialization is Computer Science & Engineering.
 
My Hometown is Matugama which is situated in the Kalutara district & i attended C.W.W. Kannangara central College,Matgama & St.Mary's Colege, Matugama.
 
I entered to the university in the Mid 2006 & will pass out in the Mid 2010.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberSandeep Ramani9 Sep '11 - 2:44 
Nice one... useful to every beginners...
Questionms outlook installation issue ?membersuis31 Mar '10 - 4:52 
hi,
i am trying to use your function in my server, but in my server there is no outlook installation,
so will this work without the outlook installation? i am getting an error in my servere "Failure sending mai" Frown | :(
 
thanks
regards
suis
AnswerRe: ms outlook installation issue ?memberHarshana Eranga Martin31 Mar '10 - 5:08 
can you be more specific and elaborate your error? May be with the stack trace and your code.
 
FYI:
 
This code has nothing to do with MS Outlook.
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.

GeneralRe: ms outlook installation issue ?membersuis31 Mar '10 - 5:50 
hi ,
you code works fine in my local machine(outlook already installed on it) under port : "587",
but when i test this function in my local server it says "Failure sending mai" is this becasue in my local server has got no outlook installed on it?
 
thanks
regards
suis
AnswerRe: ms outlook installation issue ?memberHarshana Eranga Martin31 Mar '10 - 7:06 
Definitely No. This code does not depend on MS outlook. This code is used to send an Email from an ASP.NET web application using the Gmail servers. So it does not depend/need to depend on an email client such as MS outllok,etc. If the code is working in your local machine but not in the server(I don't understand what you meant by local machine and server and their differences), it means the problem is in your code most probably.
 
The comment on the port, Gmail service can be accessed via both 465 and 587. So feel free to use any of them.
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.

GeneralRe: ms outlook installation issue ?membersuis31 Mar '10 - 22:36 
Hi,
i dont think any issues with my code, but the problem is same code running in my machine perfectly, so when i coppied the same code and trying to run in a different computer its showing me "Failure sending mail",
 
so the only difference in my machine and the other machines are bellow,
 
my machine
 
Windows XP
outlook configured
 
other machine
 
windows server 2003 64 eidtion
no outlook
 
so i can't guess what cause this error, any idea ?
thanks
regards
suis
GeneralRe: ms outlook installation issue ?memberHarshana Eranga Martin31 Mar '10 - 22:57 
Are these machines in the same network or are they in different networks? It may be a some network related issue such as proxy setting, etc which is causing this problem. Anyway I have tested this code from behind a proxy and a NAT and they worked perfectly. If both machines are in the same network I'm also clueless in that case. If they are in 2 different networks, then check the proxy settings and other related things. Theoretically it should work on any OS with the .Net framework. Btw I tested this code with .Net framework 3.5.check whether your server edition machine is equipped with it.
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.

GeneralRe: ms outlook installation issue ?membersuis31 Mar '10 - 23:09 
Hi,
these two machines are in two different network,
i think there are some issues with the smtp port that we are gonna use,
i tried bellow port number in my network
 
465
 
587
 
25
 
its all work perfectly, but in my other network its not working,
 

thanks
regards
suis
AnswerRe: ms outlook installation issue ? [modified]memberHarshana Eranga Martin31 Mar '10 - 23:25 
That should be the cause of the error you get when you try to send the email. So try to contact the network administrator and work it out with him/her and try it again. Thanks for the information.
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.
modified on Thursday, April 1, 2010 5:33 AM

GeneralRe: ms outlook installation issue ?membersuis1 Apr '10 - 5:46 
Hi Harshana,
many thanks for your followup emails,really appriciate it!
just to let you know my network administrator allowed "Telnet and SMTP in the shared firewall settings on the server." which sort out my problem,
now i can send emails using the different network too under the port id : 25
 
happy days ..... Laugh | :laugh:
 
good luck for u r career(proud to be a SL)...
 
regards
suis
AnswerRe: ms outlook installation issue ?memberHarshana Eranga Martin1 Apr '10 - 6:39 
Hi Suis,
 
Thanks a lot for letting me know of your status. So I believe now everything is working great for you Smile | :) . I'm glad to know that you are a Sri Lankan as well. If you have mentioned it before I would have help you better. Anyway thanks a lot for the wishes and I wish you the same Smile | :) .
 
Happy Hacking Big Grin | :-D
 

Thanks and Regards,
Harshana Martin
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.

Generalits greatmembermahendra_apte8510 Apr '09 - 15:08 
Thanks Yar Smile | :)
Questioncan not resolve servermemberthilina13 Mar '09 - 21:29 
The code is working when I connected with my broadband line.But when I connect via a proxy server in my office this code generates the folllowing message,
 
The remote name could not be resolved:'smtp.gmail.com'
GeneralerrormemberMember 47649556 Mar '09 - 5:23 
When i run the code end up with the following exception
 
The remote name could not be resolved:'smtp.gmail.com'
 

 

 

Dias
Sri Lanka
 
amila

AnswerRe: errormemberHarshana Eranga Martin7 Mar '09 - 0:48 
This message indicates that your DNS server was not able to resolve the Domain name "smtp.gmail.com".
 
First try this.
Type "nslookup smtp.gmail.com" in the command prompt. If this gives a IP address of Gmail smtp server you can try the program again.
If it fails again use the ip address of the gmail smtp server (which you get from the above DNS query) to replace "smtp.gmail.com" and try your program again.
 
If you get a message saying that the DNS query is unreolvable(cannot idntify the host specified or etc) it means your DNS server doesn't know how to resolve the domain name "smtp.gmail.com".
In that case you can't do nything at all. Just try to find what is the IP address of the gmail smtp server and use it instead of "smtp.gmail.com" and try your program.
 
Gud Luck Big Grin | :-D
 
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.

GeneralGood articlememberDonsw25 Jan '09 - 16:33 
THis is a good article, but you should also talk about the limitaions. I have found by using gmail or other internet mail accounts they are slow. You should talk about ways of makeing it faster such as threading. Smile | :)
GeneralThe transport failed to connect to the servermemberravifree17 Nov '08 - 4:16 
Hi,
I get an error,
"The transport failed to connect to the server"
Exception Details: System.Runtime.InteropServices.COMException: The transport failed to connect to the server
 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code
 
>>>    Line 122:            System.Web.Mail.SmtpMail.Send(Mail);
 
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433 
 
what should i do, please help me
 
ravis

AnswerRe: The transport failed to connect to the serversmemberHarshana Eranga Martin30 Nov '08 - 19:50 
This System.Web.Mail.SmtpMail.Send(Mail) is involked by using a web request to the server. So this may be a peoblem with your internet connectivity to server. otherwise this may be a problem in connecting to the server with credentials. I can't find the reason why it failed with this details. please send me the complete stack trace for the exception.
 
Make sure your internet connectivity works fine and try it again with correct gmail credentials.
 
Hope your effert will be succesful Big Grin | :-D
 
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.

GeneralGreat Work!!! and a questionmemberaakash13singh18 Oct '08 - 11:31 
hi ,
i am a student and a rookie in asp.net. This article of has been of great help as i needed to send mails in a project i hv to make as a part of my syllabus.
 
But is there any way we can send mails without using gmail credentilas or for that matter of any other service provider?
 
Can we direcly send mails by specifying the MailMessage.to , MailMessage.from and the subject, body fields.And in smtpClient specifying our system as server. By this mean if i host my application my system's IIS , then can it be done ?
 

regards
 
aakash
AnswerRe: Great Work!!! and a questionmemberKanedogg0828 Oct '08 - 14:04 
Hi aakash,
i just wanted to quickly answer your question. I believe your asking can you send email from a webpage using any type of smtp & credentials you supply?! *right?* WTF | :WTF:
 
Well in short yes mate you can, as long as the smtp server is legitimate you can do what your asking very easily. Big Grin | :-D
If you would like some suggestions or code example let us know i'll throw some up for you.
 
Hope it helps Cheers
Kanedogg!Cool | :cool:
 
"biggest fish in pond, NOT always catch the fly"

GeneralRe: Great Work!!! and a questionmemberHarshana Eranga Martin30 Nov '08 - 19:59 
Of course Big Grin | :-D
 
You can send mails with out gmail kind of public servers. Dats da easiest method. Unfortunately we cant use it always. Dats why we need gmail, yahoo public servers to work always.
 
watch this
 
http://www.asp.net/learn/videos/video-416.aspx[^]
 
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.

GeneralFailure sending Mail...memberquitchat17 Oct '08 - 19:26 
When I used the code, it was attempting to send the Email for almost 1min, and then throws an Operation Timed out Exception...
 
Please advice...
 

Thanks.
Alex.
 
http://www.hi-alex.com/

GeneralRe: Failure sending Mail...memberHarshana Eranga Martin18 Oct '08 - 2:42 
Actually i have not encountered with such an error before. So i will look in to it and help you. If some body knows the reason please help him with it. Even i need to know why.
 
Thanks.
 
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.

GeneralRe: Failure sending Mail...memberquitchat18 Oct '08 - 4:33 
Hi, actually when I used port#587 instead of port#465, it seems to be working fine...
Dunno know why...
 

Alex.
 
http://www.hi-alex.com/

AnswerRe: Failure sending Mail...memberHarshana Eranga Martin18 Oct '08 - 8:25 
Wow. Smile | :) Sound interesting. Better to check what differences are there in port 465 n 587. But anyway they have proposed both 465 n 587 for our usage.
 
Thanks.
 
Department of Computer Science & Engineering,
University Of Moratuwa,
Sri Lanka.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 10 Nov 2008
Article Copyright 2008 by Harshana Eranga Martin
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid