ASP.NET 2.0 aka System.Net.Mail with GMail

We recently dropped one of our commercial libraries, the Rebex.Net.Mail Tool. Instead we are using the build in System.NET.Mail Class from ASP.NET 2.0. In ASP.NET 1.1 you were able to use the System.Web.Mail Class and you were able to send mail via GMail by adding those filters:

 

ASP.NET v1.1:

            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            // - smtp.gmail.com use smtp authentication
            mailMsg.Filters.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            mailMsg.Filters.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "xx");
            mailMsg.Filters.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "xx");
            // - smtp.gmail.com use port 465 or 587
            mailMsg.FiltersAdd("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
            // - smtp.gmail.com use STARTTLS (some call this SSL)
            mailMsg.Filters.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
            // try to send Mail

As I switched to the new ASP.NET 2.0 System.Net.Mail class the filters function was gone. Important: mailMsg.Headers.Add in the new class is not the equivalent class to that Filters.Add method, that’s what I thought, too, in the beginning.

In fact it got much easier now, but totally different:

ASP.NET v2.0:

 // Smtp configuration
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";

        smtp.Credentials = new System.Net.NetworkCredential("xx", "xx");
        smtp.EnableSsl = true;   

I’d love to have more specific documentations on those changes, but thanks to Microsoft for making our code smaller once again ;).

44 comments ↓

#1 Mike on 03.10.07 at 5:48 am

Hi, Andreas:

Sorry to bother you.

I have copied you second source code and tested it with asp.net2.0& win XP. But it failed. On my laptop I can use outlook2003 to send email. If you are avaiable, could you help me figure it out(or test it on you computer).:lol: I have enclosed the source code & exception below.

I am looking forward to getting any feedback from you.

Thanks in advance and have a nice weekend.

Mike

:roll::roll::roll::roll::roll:
SmtpClient smtp = new SmtpClient();
smtp.Host = “smtp.gmail.com”;
smtp.Port = 465;

smtp.Credentials = new System.Net.NetworkCredential(“uid”, “pwd”);
smtp.EnableSsl = true;
System.Net.Mail.MailMessage message = new MailMessage(“ee@hotmail.com”, “ee@hotmail.com”, “Subject”, “Body”);
message.BodyEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
try
{
smtp.Send(message);
Response.Write(“Email successfully sent.”);
}
catch (Exception ex)
{
Response.Write(“Send Email Failed.” + ex.ToString()); ;
}
:oops::oops::oops::oops:
Send Email Failed.System.Net.Mail.SmtpException: The operation has timed out. at System.Net.Mail.SmtpClient.Send(MailMessage message) at MainPage.Button1_Click(Object sender, EventArgs e) in c:\Programming in Class\ThreePages\MainPage.aspx.cs:line 111

#2 andreas.kraus on 03.10.07 at 9:45 am

Hi Mike,

no problem. Did you try leaving out the smtp.Port? Google says they are using Port 465 or 587. The example works here.

It sounds like something is blocking your request, maybe a firewall?

Best regards,
Andreas

#3 David on 03.23.07 at 9:57 pm

Mike:
I was having the exact same timeout issue, but when I switched to port 587, it started working… a little odd since my firewall was turned off, but as long as 587 works, I’m happy. Something else to keep in mind–I was testing by using my gmail account in the “from” address and sending to my work email address. I wasn’t getting any of those emails. I’m guessing SMTP relay is turned off on our Exchange server, but I don’t really know. I then tried sending from my Gmail account TO my gmail account, and all of a sudden it was working. HOORAY! Hope this helps 🙂

#4 G on 03.30.07 at 9:06 pm

I’m not sure what anti-spam measures Google has taken, but I believe some of these errors are due to their mail/spam filtering system. I’ve been able to get some of my code to work fine, but after a few test messages it stops to work completely. Logging in to Gmail ‘manually’ I see a lot of the messages have been blocked, “PERM_FAILURE: Message rejected for Sector 5 policy reasons”, which I think means they have flagged your account as a possible spammer account. Anyone else agree with this observation? I’ll try again tomorrow with a different recipient/subject/body to try to figure out the rhyme or reason…

#5 andreas.kraus on 03.31.07 at 7:07 am

GMail has a limit, 500 mails per day and you may not send too many mails to e-mail addys which do not exist. Both actions will result in a temporary block until the end of the day..

#6 Mekala.G on 05.12.07 at 9:09 am

Hi,
I have used Your coding to send mail,but It shows the following error
System.Net.Mail.SmtpException: The operation has timed out. at System.Net.Mail.SmtpClient.Send(MailMessage message) at _Default.btSend_Click(Object sender, EventArgs e) in d:\IW-Workspace\Mekala\Examples\SendMail\Mail.aspx.cs:line 41Mail Sending Fail’s

I dont Know why this error.
And my port No is 465.
I send email from my gmail id to another one gmail Id only .For this what should be the port No in IIS?.
Please Help me to solve this error.
Thanks and Regards,
Mekala.G

#7 Ashfaq Ahmed on 05.30.07 at 9:47 am

Gmail SMTP port 587 works OK with above code.

#8 VerbatimBOT on 06.03.07 at 3:07 pm

Yeap, that work’s fine with 587 port!
Thanks!

#9 Helgeduelbeck on 06.20.07 at 2:48 pm

Hi Andre,

It’s not about the port,
but STARTTLS command that gmail needed.
It’s ok for yahoo.com.sg user (yahoo singapore), but I’ve trouble for gmail.com regarding STARTTLS.
In my web.config I wrote this for login page, session ‘forget your password’.

for yahoo.com.sg :

for gmail.com :


😕

I don’t know how to put the attribute ‘port’ and ‘ssl’ for gmail on that config. would you help me ?

#10 andreas.kraus on 06.20.07 at 3:56 pm

Hello Helgeduelbeck,

if you use ASP.NET v2.0 please try using the second method I mentioned in my post. The advantage is that ASP.NET takes care about all the authentication stuff.

hth,
Andreas

#11 arun k on 08.18.07 at 7:06 am

I’m using asp.net 2.0 to sent mail through gmail settings..I have done every thing said above. But i’m getting the following exception: “The remote name could not be resolved: ‘smtp.gmail.com’ ” I’m connecting to the internet through a proxy server. So probably thats the problem. How do i give the proxy ip & authentication through asp.net?

#12 Bharath on 09.13.07 at 11:39 am

protected void btnSend_Click(object sender, EventArgs e)
{
SmtpClient client = new SmtpClient();
MailMessage mail = new MailMessage();

client.Host = “smtp.gmail.com”;
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential(“uid”, “pwd”);
client.EnableSsl = true;

MailAddress fromaddress = new MailAddress(txtFrom.Text.ToString(), txtFromName.Text.ToString());

mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.From = fromaddress;
mail.To.Add(“test@gmail.com”);
mail.Subject = txtSubject.Text.ToString();
mail.Body = txtMessage.Text.ToString();
mail.Priority = MailPriority.High;
mail.IsBodyHtml = false;

lblStatus.Visible = true;

try
{
client.Send(mail);
lblStatus.Text = “Status: Your Mail has been sent..”;
}
catch (Exception ex)
{
lblStatus.Text = “Status: Unable to send mail…” + ex.Message ;
}
}

This is my Code. Am getting the error as “Failure sending mail”, inner exception message as “Unable to connect to the remote server” and the inner exception as “InnerException = {“No connection could be made because the target machine actively refused it”}”

where the problem is ?

#13 menty on 10.01.07 at 2:04 pm

Thank you for this artikle and its replies. I was trying to get my smtpclient to work with gmail for 2 days now. The important hint was the 587 port instead 465 like described in gmail documentations. I discoverd that I had trouble with our exchange server like David posted, either.

Now every thing works fine!

@arun k:
try smtp.googlemail.com instead of smtp.gmail.com

#14 andreas.kraus on 02.07.08 at 1:32 pm

Sorry Jags, I need to know the error otherwise I can’t help you..

#15 Syed on 02.13.08 at 1:28 pm

Hi,

i am writing mail code using Syste.Net.Mail (VS2005) mail class .it will work in my machine , but it will not working some other machine .i am using “smtp.google.com” mail server. it wiil be in webservices. Please give me a clue for this problem .

Regadrs

Syed. B

#16 Soumya on 02.21.08 at 12:42 pm

Hello Sir,
This is working fine on local host. but not working on the Hosted Server.May you please help me.

Thanks.

Soumya

#17 Kasim on 03.27.08 at 1:53 pm

Hello,

The reason of all that failures on remote machines could be Firewall. Try to add 587 port to allowed.
Hope this helps.

Regards,
Kasim

#18 Murugan on 03.28.08 at 8:51 am

Hai…
Please send me, code for verify the mail was send or not. How can i find out mail send? without try-catch statement

#19 Amol on 04.06.08 at 8:09 am

i did all the things but its not working
i want to know about which user name and password
should i pass whether its my mail account or for my connection establishment account given by my ISP

#20 Rico on 04.07.08 at 9:56 pm

Could someone please layout the entire working code. These little snippets of code are not working and i am continuously running into errors. Please and thank you.

#21 Mehul on 04.14.08 at 7:37 pm

can i get the entire code in ASP.NET 2.0 in C#.And also code of web.config file.

#22 Mehul on 04.14.08 at 7:39 pm

can i get the entire code in ASP.NET 2.0 in C#.And also code of web.config file.And the total informaton to how to use gmail to send mail from website

#23 Jags on 04.16.08 at 1:54 pm

it worked, there was some problem at my workplace due to firewall

#24 Olga on 05.05.08 at 7:21 am

Hi!
I am getting the following error
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
Could you help please?

#25 Lito Malone on 05.05.08 at 11:38 pm

no man… i’m try in many forms… and find this way…

SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Port = 587;
smtp.Host = “smtp.gmail.com”;
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential(“user@yourdomain.com”, “password” );

ENJOY Friends !

#26 Carolyn on 05.06.08 at 4:43 pm

If I use 465, I got “No connection could be made because the target machine actively refused it”.

If I use 587, I got “the operation has timed out”.

My firewall is turned off. Any ideas on what’s wrong?

#27 Shekhar on 05.09.08 at 10:14 am

hi
i want that email should go to client after finishing all uploading file at the end of the days

can any body give me some idea or code for that one plz

thank you

#28 Pranav Mistry on 05.19.08 at 6:53 am

If I use 587, I got “No connection could be made because the target machine actively refused it 74.125.47.111:587 ”.

If I use 465, I got “the operation has timed out”.

#29 Dondre on 07.13.08 at 5:53 am

Man, I’m having the same problem Pranav Mistry. Is Gmail dead? It’s been 3 days of no luck, that code doesn’t work. Maybe it used to, this thread is over a year old. Jesus Christ this sucks!

#30 kamran on 08.08.08 at 8:28 pm

thank you for all the help. i just have a small problem. gmai is showing message delivery failure. i m using same accoumt for receiving and sending.
thanks in advance

#31 kamran on 08.08.08 at 8:30 pm

sorry sorry. i m sending message on hotmail and through my gmail account.
thanks

#32 kamran on 08.08.08 at 8:33 pm

“Google tried to deliver your message, but it was rejected by the recipient domain. We recommend contacting the other email provider for further information about the cause of this error. The error that the other server returned was: 550 550 Requested action not taken: mailbox unavailable (state 14).

this is the error google is displaying.

#33 kamran on 08.08.08 at 8:43 pm

i changed the both emails to gmail but it did not help please tell me so that i can fix this as soon as possible.

#34 Shakeel on 09.15.08 at 11:45 am

But what about smtp Yahoo ,this give timeout problem.

#35 sayish on 09.18.08 at 12:33 pm

SmtpClient sc = new SmtpClient();
sc.EnableSsl = true;
System.Net.NetworkCredential(“xx”, “xxxxxx”);
sc.Send(mailmsg);

Port 465 and 587 not working!!!!!!!!!!!!!!!!

#36 Bojan on 09.27.08 at 12:21 pm

THANKS

:DDDD

IT WORKS PERFECTLY PORT=587

#37 Naresh on 11.01.08 at 7:17 pm

hi guys
i am using system.web.mail class its working for gmail but its not working for yahoo and other pls tell me why pls help

send me answer to my mail id nab_d25e15@yahoo.co.in

#38 jack on 11.14.08 at 9:55 am

hey thz very much! i like yr example
i have been trying to do like this.and finding examples but they don’t really work like this.
but it doesn’t work with port 465, why?
please email me back.

#39 Amol on 12.29.08 at 7:32 am

I m sending mail with mutlithreading for autosend.
but Mail.SmtpException: The operation has timed out. at System.Net.Mail for port 25.
and no connection established for port 465 and port 587 what should i do.
any help would be appreciable.

#40 Victor on 01.10.09 at 7:50 pm

need coment
//smtp.EnableSsl = true;

#41 Bhavesh on 01.30.09 at 2:51 pm

It’s error showing Unable to reply all receiptants.

Thanks,
Bhavesh

#42 kingsley on 01.31.09 at 9:40 pm

I am also getting the same error. System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

i am using smtp.gmail.vom and port number 587. it worked for a few days and now it is not working. i dont know why.

does anyone have any tips?

#43 ram on 02.17.09 at 1:36 pm

dfsgsd

#44 Richard on 03.24.10 at 10:00 am

Hi Guys

I’m trying to get my SmtpClient to send mail. However, I am behind a proxy server. When I connect directly to the internet, everything works fine. But at the office, where I’m behind a proxy server, it doesn’t work.

Does anyone here know how to authenticate with the proxy server before trying send the email?

Leave a Comment