I am trying to create a small app using C# to send email, but I can’t get it to work even using port 587 (GMail) TLS or 465 (GMail SSL). I’m not sure what is causing my problem, should I edit my app.config file? Here is my code:

try
{
  SmtpClient client = new SmtpClient("smtp.gmail.com", 465);
  client.EnableSsl = true;
  client.Timeout = 10000;
  client.DeliveryMethod = SmtpDeliveryMethod.Network;
  client.UseDefaultCredentials = false;
  client.Credentials = new NetworkCredential("myemailid", "mypwd");

  MailMessage msg = new MailMessage();
  msg.To.Add(txtTo.Text);
  msg.From = new MailAddress("myemailid");
  msg.Subject = txtSub.Text;
  msg.Body = txtMsg.Text;

  client.Send(msg);
  MessageBox.Show("sent");
}
catch (Exception ex) 
{
    MessageBox.Show(ex.Message);
}

Luaan's user avatar

Luaan

62.4k7 gold badges97 silver badges117 bronze badges

asked Jun 30, 2014 at 7:34

user3774291's user avatar

8

Ports 25 & 465 caused problems. Changing port to 587 worked for me.

Dim myCredential As System.Net.NetworkCredential
myCredential = New System.Net.NetworkCredential("emailid", "pwd")
smtp.Host = "server"
smtp.Port = 587
smtp.EnableSsl = True
smtp.UseDefaultCredentials = False
smtp.Credentials = myCredential
smtp.Send(mm)

answered Mar 4, 2020 at 4:20

Suresh Nair's user avatar

If you are getting a timeout exception, then it means that the SmtpClient was unable to either connect to the SMTP server or the connection was lost at some point during the send.

This could be caused by a firewall on your end that is blocking outgoing connections to the server or blocking outgoing connections on port 465.

answered Jul 5, 2014 at 11:02

jstedfast's user avatar

jstedfastjstedfast

36k5 gold badges97 silver badges110 bronze badges

4

I had the same issue, running it as Administrator sorted it for me

answered Dec 10, 2019 at 12:10

Nathan Hadley's user avatar

  1. Allow ports 25, 465, 587 on Firewall setting.

  2. I could send mail by System.Net.Mail.SmtpClient or MailKit.Net.Smtp.SmtpClient

    In some mail services such as aruba.it, System.Net.Mail.SmtpClient does not work at all.

Following is the code part using MailKit.Net.Smtp.SmtpClient

using MailKit.Security;
using MimeKit;
using MailKit.Net.Smtp;
using MimeKit.Text;
using System;
using System.Net.Mail;
...
// create email message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse("[email protected]"));
//email.From.Add(MailboxAddress.Parse("[email protected]"));// if you want to use gmail service, enable this line.
email.To.Add(MailboxAddress.Parse(destinatario));
email.Subject = oggetto;
email.Body = new TextPart(TextFormat.Html) { Text = "<h1>Example HTML Message Body</h1>" };
if (password.Length > 0)
{
    msg += "Password : " + password;
}

if (link.Length > 0)
    email.Body = new TextPart(TextFormat.Html) { Text = messaggio + "<a href=\"" + link + "\"" + ">Clicca qui</a>" + msg }; 
else
    email.Body = new TextPart(TextFormat.Html) { Text = messaggio }; 

// send email
var smtp = new MailKit.Net.Smtp.SmtpClient();
smtp.Connect("smtps.aruba.it", 465, SecureSocketOptions.SslOnConnect); 
smtp.Authenticate("[email protected]", "password");
//smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);// if you want to use gmail service, enable this line.
//smtp.Authenticate("[email protected]", "password");// if you want to use gmail service, enable this line.
smtp.Send(email);
smtp.Disconnect(true);

Following is the code part using System.Net.Mail.SmtpClient

using System;
using System.Net.Mail;
...
try
{
    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;
    mail.From = new MailAddress(strFromMail);
    mail.To.Add(new MailAddress(strToMail));
    mail.Subject = oggetto;
    mail.Body = messaggio;

    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 25/* or 587 */);
    System.Net.NetworkCredential basicCredential1 = new System.Net.NetworkCredential(strFromMail, "password");
    client.EnableSsl = true;
    client.UseDefaultCredentials = false;
    client.Credentials = basicCredential1;
    
    client.Send(mail);
}
catch (Exception ex)
{
    MessageBox.Show("Error sending email \n"+ex.ToString());
}

answered Jan 20, 2021 at 9:03

persec10000's user avatar

persec10000persec10000

8302 gold badges10 silver badges17 bronze badges

Есть почта shop@m***c.ru , делегированная на почтовый сервис mail.ru (название сайта за***). Мне нужно для него сделать подключение SMTP на m***c.ru. Я создал в настройках почты пароль для приложений. У них есть инструкция по настройке. Согласно ней, параметры подключения:

SMTP host: smtp.mail.ru
Port: 465
“Use Secured Connection” и “Use authentication” (пробовал все 4 варианта)
Login: shop@m***.ru
Password: •••••••••••••••••••• (пробовал и пароль приложения, и пароль почты)
Email from: shop@m***c.ru

При проверке на специальном сервисе результат всегда один:

SMTP send error
The operation has timed out.

При попытке забить эти параметры на сайте, сайт зависает, что подтверждает правильность этой ошибки.
Что я делаю не так?


  • Вопрос задан

  • 129 просмотров

Сделайте простейшую проверку, на вашем сервере запустите telnet smtp.mail.ru 465. Сразу увидите, есть коннект на их сервер, или что-то связь конкретно блокирует…

Пригласить эксперта


  • Показать ещё
    Загружается…

07 окт. 2023, в 06:39

30000 руб./за проект

07 окт. 2023, в 01:05

4500 руб./за проект

07 окт. 2023, в 00:28

3000 руб./за проект

Минуточку внимания

SMTPException is a common error encountered by email marketers and developers who use Simple Mail Transfer Protocol (SMTP) to send emails from their applications. One of the most frustrating SMTPException errors is ‘The operation has timed out’ error. This article explores the causes, symptoms and solutions for this error.

Causes of ‘The operation has timed out’ Error

SMTP servers have an inherent feature that limits the amount of time a request can take before it times out. The duration of this timeout varies depending on the provider and the server configuration. The main causes of ‘The operation has timed out’ error include:

  • Slow or unstable network connections that slow down the rate at which requests are sent and received.
  • Congested network conditions that cause delays in packet transmissions and receipt of server responses.
  • Overburdened mail servers that are overloaded with concurrent requests and cannot respond to individual requests within reasonable time limits.
  • Application bugs and errors such as faulty code or insufficient SMTP communication settings.

Symptoms of ‘The operation has timed out’ Error

Some of the common symptoms of ‘The operation has timed out’ error include:

  • Failure to establish a connection to the SMTP server.
  • Partial or complete interruption of email transmission from the email client to the SMTP server.
  • Delayed or undelivered email messages, which may result in lost business opportunities or communication breakdowns.

Solutions for ‘The operation has timed out’ Error

If you encounter ‘The operation has timed out’ errors in your email marketing or development applications, there are a number of solutions you can try to resolve the issue. Here are some proven solutions:

1. Optimize Network Performance

Improve your network connectivity by optimizing your network settings or upgrading your internet connection speed. You can also try using a different network connection, such as Ethernet instead of Wi-Fi.

2. Increase Server Timeout Duration

Increase the duration of the server timeout from your application’s SMTP configuration settings. This will give the server more time to respond to requests and reduce the likelihood of timeouts.

3. Reduce Traffic on the SMTP Server

Reduce the load on the SMTP server by adjusting the time intervals between requests, throttling the number of concurrent connections or reducing the frequency of email transmission.

4. Use a Different SMTP Provider

Try connecting to a different SMTP provider with better performance and lower latency. This could help resolve the timeout issues caused by slow, congested, or overloaded servers.

5. Check Your Application Code

Review your application code for any errors or coding inefficiencies that may cause the SMTPException error. You can ask a professional developer to review your code for you or use debugging tools such as log files to identify any bugs or issues.

In conclusion, SMTPException errors can cause frustration for developers, marketers and email clients alike. By following the above solutions, you can resolve ‘The operation has timed out’ errors and ensure that your email communication is uninterrupted and reliable.

  • User-434868552 posted

    @ matrix388

    if it’s your isp delaying you, increasing the length of the SMTP timeout may not be desirable …

    it would be better to increase the amount of time sleeping between sending each e-mail …

    TIMTOWTDI   =.   there is more than one way to do it

    i prefer a timeout not longer than 15 secords … what i might do it this …

    (a) create a list of failed e-mails …

    (b) for every timeout failure, add to the list whatever information you require to resend the e-mail …

         for example:   List<FailedEmail> where FailedEmail is an object that you have defined.

    (the reason for List<FailedEmail> is so that you do not have to requery your database)

    (c) when you’ve finished all the the items from your database, process your List<FailedEmail> …

    (d) remove items one at a time from List<FailedEmail>, send the email … if it fails, add it back to your List<FailedEmail>.

    (e) repeat until List<FailedEmail> is empty.

      —

    Other options:

    (i) have your own dedicated server (i use corenetworks.net)

    (ii) use an e-mail service that lets you use a higher throughput volume

    (iii) have several accounts with your isp … send the first e-mail using account a, the second using account b, … then back to account a, et cetera until you’ve processed all of your e-mails … this may or may not work … it depends upon how your isp
    has set up e-mail throttling … again, you need to talk to Saudi Aramco … likely, they will work with you (unless you start to spam and then they’ll likely delete your e-mail account).

    g.

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • I think this is the famous SSL issue of System.Net.Mail

    System.Net.Mail with SSL to authenticate against port 465

    You should use some external library or wait until Microsoft include this features in a framework release

    Related videos on Youtube

    Send Web Page Through Godaddy eMail SMTP (asp.net, c# WebRequest)

    02 : 32

    Send Web Page Through Godaddy eMail SMTP (asp.net, c# WebRequest)

    Haritha Computers & Technology

    Chapter 21: Send Email using Gmail SMTP in C# | GoDaddy SMTP | Office 365 SMTP

    09 : 14

    Chapter 21: Send Email using Gmail SMTP in C# | GoDaddy SMTP | Office 365 SMTP

    Laughing Technologies (OkTests.com)

    Send mail imap goodady from c# / Enviar correo IMAP goodady desde c# csharp

    05 : 36

    Send mail imap goodady from c# / Enviar correo IMAP goodady desde c# csharp

    How To Send Godaddy SMTP eMail Setup Host & Port (asp.net, c#)

    03 : 00

    How To Send Godaddy SMTP eMail Setup Host & Port (asp.net, c#)

    Haritha Computers & Technology

    Setting Up SMTP with Cpanel Hosting

    02 : 29

    Setting Up SMTP with Cpanel Hosting

    The server response was 5.5.1 Authentication Required gmail send asp.net

    04 : 09

    The server response was 5.5.1 Authentication Required gmail send asp.net

    Haritha Computers & Technology

    [SOLVED] The Wait Operation Timed Out Error Problem Issue

    05 : 58

    [SOLVED] The Wait Operation Timed Out Error Problem Issue

    How To Send SMTP eMail Setup Host & Port (MVC, asp.net) - godaddy

    15 : 59

    How To Send SMTP eMail Setup Host & Port (MVC, asp.net) – godaddy

    Haritha Computers & Technology

    Send eMail With Attachment (asp.net, c#) code SMTP Server Godaddy

    04 : 39

    Send eMail With Attachment (asp.net, c#) code SMTP Server Godaddy

    Haritha Computers & Technology

    Godaddy Hosting Timeout

    00 : 36

    SendGrid tutorial (2021) - Send emails from a C# project using SendGrid and custom Godaddy domain

    11 : 29

    SendGrid tutorial (2021) – Send emails from a C# project using SendGrid and custom Godaddy domain

    Comments

    • I am using following peace of code to send mail using godaddy hosting .

      but its throw System.Net.Mail.SmtpException: The operation has timed out.

      protected void sendmail()
          {
              var fromAddress = "[email protected]";
              // any address where the email will be sending
              var toAddress = "[email protected]";
              //Password of your gmail address
              const string fromPassword = "mypassword";
              // Passing the values and make a email formate to display
              string subject = "HI test mail ";
              string body = "From: [email protected]";
              // smtp settings
              var smtp = new System.Net.Mail.SmtpClient();
              {
                  //smtp.Host = "relay-hosting.secureserver.net";
                  smtp.Host = "smtpout.secureserver.net";
                  smtp.Port = 80;
                  smtp.EnableSsl = true;
                  smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                  smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                  smtp.Timeout = 20000;
              }
              // Passing values to smtp object
              smtp.Send(fromAddress, toAddress, subject, body);
          }
      

      • I believe smtp port with ssl should be 465

      • Why not check with the people who run your SMTP server which port you’re meant to be using? There’s nothing wrong with the code, so asking here is pointless – all we can do is guess your network config.

    • LOL. How about “client.Timeout = int.MaxValue;”?

    • That link is dead.

    • @Dunc not anymore! god saves the internet archive

    Recents

    Related

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *