2

So i've been searching stackoverflow for a way to send emails using a gmail account via a asp website...

I've tried many ways including Sending email in .NET through Gmail which seemed to be the best due to amount of upvotes he got.

However sadly it still doesn't work for me! I keep getting a time out.

Here's my code:

 var fromaddress = new MailAddress("[email protected]", "from");
 var toaddress = new MailAddress("[email protected]", "to");
 try
 {
     using (var smtpClient = new SmtpClient())
     {              
         smtpClient.EnableSsl = true;
         using (var message = new MailMessage(fromaddress, toaddress))
         {
             message.Subject = "Test";
             message.Body = "Testing this shit!";
             smtpClient.Send(message);
             return true;
         }
     }
 }
 catch (Exception ex)
 {
     return false;
 }

in my web.config I have

  <system.net>
    <mailSettings>
      <smtp from="[email protected]" deliveryMethod="Network">
        <network userName="[email protected]" password="mypassword" host="smtp.gmail.com" port="587"/>
      </smtp>             
    </mailSettings>
  </system.net>

According to several sites i've visited this should work!!! .. but it doesn't.

Is there still anything i'm doing wrong?

2
  • 3
    you are not even logging the exception, you just return false and not write exception details, message, stacktrace anywhere... anything can happen and you simply never know what. I suggest you to catch the exception properly and log it to a log file. Commented Dec 1, 2011 at 9:23
  • @Davide: Since this is only testing and I'm only getting back timeouts.. it doesn't really matter what I do with the exception. Currently it's only there so I can see the exception with a breakpoint. Commented Dec 1, 2011 at 9:27

6 Answers 6

2

You never set the login add this before your smtpClient.Send() Method.

NetworkCredential NetCrd = new NetworkCredential(youracc, yourpass);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = NetCrd;

Load the web.config via ConfigurationManager if it does not work automatically.

Sign up to request clarification or add additional context in comments.

5 Comments

If he doesn't set the credentials in the code, the ones set in the config would be used.
@Grrbrr404 Is there any limitation using gmail to send emails ?
RoyiNamir You mean in mail size or something like that? I dont know im sorry. @Edgar if thats true then the problem is maybe Port 587 - He should check his network configuration or post a detailed exeption message
@Grrbrr404 Also , but I meant to number of emails which i can produce throught gmail
All i'm getting is: "The operation has timed out."
1

As suggested on this page, try installing telnet to see if you can connect to the mail server. It could be a firewall issue on your server. You can also try using another port as suggested in the link.

6 Comments

Is there any limitation using gmail to send emails ?
@RoyiNamir not as far as I know. I have used gmail to send emails many times in the past, with success.
Is there any limitation of the Number of emails which I can send ?
Also Can I send a mail to xxx as if [email protected] sent it ? ( does it allows you to do that? ) - in the from field
@RoyiNamir a quick search suggests that there are some limitations: mail.google.com/support/bin/answer.py?answer=22839
|
1

Your code seems fine to me.

Try to deliberately enter false credentials. If you get a different errormessage you are connected to gmail and there is a problem there.

If you get the same timeout problem, it is probably not a software thing but a firewall issue.

longshot - update Perhaps there is a web.config issue? Try to specify everything in code like this. I have this working in real life with Gmail so if this does not work it definitely is a firewall/connection thing.

           SmtpClient mailClient = new SmtpClient();
            //This object stores the authentication values     
            System.Net.NetworkCredential basicCredential =
                new System.Net.NetworkCredential("[email protected]", "****");
            mailClient.Host = "smtp.gmail.com";
            mailClient.Port = 587;
            mailClient.EnableSsl = true;
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            mailClient.UseDefaultCredentials = false;
            mailClient.Credentials = basicCredential;


            MailMessage message = new MailMessage();

            MailAddress fromAddress = new MailAddress("[email protected]", "Me myself and I ");
            message.From = fromAddress;
            //here you can set address   
            message.To.Add("[email protected]");
            //here you can put your message details

            mailClient.Send(message);

Good luck..

2 Comments

Still a time out.. so I guess I have to fix the firewall. Sadly, i'm at school at the moment so I doubt I can change anything about it unless it's my personal firewall. So i'll try the same on the server now and see what happens there, assuming the settings there are correct for sendings mails.
So most probably a firewall issuye. Have a look at the code I posted to doublecheck that your web.config is not the issue.
0

Can you try this out?

            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();
                try
                {
                    MailAddress fromAddress = new MailAddress(ConfigurationManager.AppSettings["fromAddress"], ConfigurationManager.AppSettings["displayName"]); //Default from Address from config file
                    MailAddress toAddress = new MailAddress("[email protected]", "from sender");

                    // You can specify the host name or ipaddress of your server
                    // Default in IIS will be localhost 
                    smtpClient.Host = ConfigurationManager.AppSettings["smtpClientHost"];


                    //Default port will be 25
                    smtpClient.Port = int.Parse(ConfigurationManager.AppSettings["portNumber"]); //From config file

                    //From address will be given as a MailAddress Object
                    message.From = fromAddress;

                    // To address collection of MailAddress
                    message.To.Add(toAddress);
                    message.Subject = ConfigurationManager.AppSettings["Subject"]; //Subject from config file

                    message.IsBodyHtml = false;

                    message.Body = "Hello World";
                    smtp.DeliveryMethod = SmtpDeliveryMethod.NetWork                    
                    smtpClient.Send(message);
                }
                catch (Exception ex)
                {
                   throw ex.ToString();
                }

The configuration settings would be,

<configuration>
    <appSettings>
        <add key="smtpClientHost" value="mail.localhost.com"/> //SMTP Client host name
        <add key="portNumber" value="25"/>
        <add key="fromAddress" value="[email protected]"/>
        <add key="displayName" value="Auto mail"/>
        <add key="Subject" value="Auto mail Test"/>
    </appSettings>

</configuration>

4 Comments

Can you try now? I have added a line which i have forgotten. smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis; This works for me to any web sever (I have tested with gmail, yahoo and hotmail)
Have you included, using System.Net.Mail; at the top?
Please note: I have not included "NetworkCredential" which is not required
I have modified my code again. Can you please try that? the new one added is: smtp.DeliveryMethod = SmtpDeliveryMethod.NetWork; you might need the network credentials as well if not supplied.
0

Put these settings EnableSSL = true and defaultCredentials="false" in your web.config settings. Gmail smtp server requires SSL set to true and mailclient.UseDefaultCredentials = false should be false if you are providing your credentials.

Update Web.Config Settings:

<mailSettings>
  <smtp from="[email protected]" deliveryMethod="Network">
    <network userName="[email protected]" password="mypassword" host="smtp.gmail.com" defaultCredentials="false" port="587" enableSsl="true"/>
  </smtp>             
</mailSettings>

And check this shorter code to send mail after providing settings in the web.config. even it send email much fast rather then specifying setting while creating the smtpclient setting in the mail sending function.

Public void SendEmail(string toEmailAddress, string mailBody)
        {
            try
            {
                MailMessage mailMessage = new System.Net.Mail.MailMessage();
                mailMessage.To.Add(toEmailAddress);
                mailMessage.Subject = "Mail Subjectxxxx";
                mailMessage.Body = mailBody;
                var smtpClient = new SmtpClient();
                smtpClient.Send(mailMessage);
                return "Mail send successfully";
            }
            catch (SmtpException ex)
            {
                return "Mail send failed:" + ex.Message;
            }

Working very much fine at my side..

Comments

-1
var smtpClient = new SmtpClient(gmailSmtpServer, gmailSmtpPort)
{
   Credentials = new NetworkCredential(FromGEmailAddress, FromGEmailAddressPassword),
   EnableSsl = true
};

try
{
    using (var message = new MailMessage(fromaddress, toaddress))
    {
      message.Subject = "Test";
      message.Body = "Testing this shit!";
      smtpClient.Send(message);
     return true;
    }
}
catch (Exception exc)
{
  // error
  return false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.