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("from@gmail.com", "from");
 var toaddress = new MailAddress("to@address.com", "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="from@gmail.com" deliveryMethod="Network">
        <network userName="from@gmail.com" 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?

Community
  • 1
  • 1
Theun Arbeider
  • 5,259
  • 11
  • 45
  • 68
  • 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. – Davide Piras Dec 01 '11 at 09: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. – Theun Arbeider Dec 01 '11 at 09:27

6 Answers6

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.

Grrbrr404
  • 1,809
  • 15
  • 17
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.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • Is there any limitation using gmail to send emails ? – Royi Namir Dec 01 '11 at 09:29
  • @RoyiNamir not as far as I know. I have used gmail to send emails many times in the past, with success. – Klaus Byskov Pedersen Dec 01 '11 at 09:33
  • Is there any limitation of the Number of emails which I can send ? – Royi Namir Dec 01 '11 at 09:34
  • Also Can I send a mail to xxx as if BillGates@microsoft.com sent it ? ( does it allows you to do that? ) - in the from field – Royi Namir Dec 01 '11 at 09:35
  • @RoyiNamir a quick search suggests that there are some limitations: http://mail.google.com/support/bin/answer.py?answer=22839 – Klaus Byskov Pedersen Dec 01 '11 at 09:37
  • @RoyiNamir: yes, you can send from any e-mail address. However, any SMTP server will allow that without additional security configuration. Smart email clients (like gmail) will show a message "this mail might not be send from ...." if they do a reverse lookup – Pleun Dec 01 '11 at 09:46
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("username@mydomain.com", "****");
            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("info@mydomain.com", "Me myself and I ");
            message.From = fromAddress;
            //here you can set address   
            message.To.Add("to@you.com");
            //here you can put your message details

            mailClient.Send(message);

Good luck..

Pleun
  • 8,856
  • 2
  • 30
  • 50
  • 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. – Theun Arbeider Dec 01 '11 at 09:55
  • So most probably a firewall issuye. Have a look at the code I posted to doublecheck that your web.config is not the issue. – Pleun Dec 01 '11 at 10:46
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("abc@gmail.com", "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="defaultSender@gmail.com"/>
        <add key="displayName" value="Auto mail"/>
        <add key="Subject" value="Auto mail Test"/>
    </appSettings>

</configuration>
CodeMad
  • 950
  • 2
  • 12
  • 30
  • 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) – CodeMad Dec 01 '11 at 09:45
  • Have you included, using System.Net.Mail; at the top? – CodeMad Dec 01 '11 at 09:49
  • Please note: I have not included "NetworkCredential" which is not required – CodeMad Dec 01 '11 at 09:52
  • 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. – CodeMad Dec 01 '11 at 10:10
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="from@gmail.com" deliveryMethod="Network">
    <network userName="from@gmail.com" 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..

Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
-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;
}
Elias Hossain
  • 4,410
  • 1
  • 19
  • 33