1

Делаю так:

public static void SendEmailAsync(string email, string subject, string message)
{
    MailMessage mail = new MailMessage("***@gmail.com",email);
    mail.Body = message;
    mail.Subject = subject;
    SmtpClient smtp = new SmtpClient("smtp.gmail.com",465);
    smtp.EnableSsl = true;
    smtp.Credentials = new NetworkCredential("***@gmail.com", "mypass");  
    try
    {
        smtp.Send(mail);
    }
    catch (Exception ex)
    {
        Exception ex2 = ex;
        string errorMessage = string.Empty;
        while (ex2 != null)
        {
            errorMessage += ex2.ToString();
            ex2 = ex2.InnerException;
        }                
    }
}

Вылетает в catch с сообщением

{System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: The connection was closed. at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine) at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller) at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.Send(MailMessage message) at site.EmailService.SendEmailAsync(String email, String subject, String message) in C:\Users\Виталий\source\repos\site\site\EmailService.cs:line 64}

Помогите разобраться в чем проблема

2 ответа 2

1

По моему, проблема в порте, должно быть 587 а не 465:

SmtpClient smtp = new SmtpClient("smtp.gmail.com",587);

Read Gmail messages on other email clients using POP

1
  • Спасибище :) Самое интересное то - что я подсмотрел данный порт в гугл хелпере, но да ладно 24 дек 2018 в 17:01
1

Готовый рабочий класс (работает уже больше 5 лет)

    using System;
    using System.IO;
    using System.Net.Sockets;
    using System.Net;
    using System.Text;
    using System.Collections;
    using System.Collections.Generic;
    using System.Windows.Forms;

    namespace AeroAdmin
    {

public class clsMail
{
    public static string Subject
    {
        set{m_subject=value;}
    }

    public static string To_name
    {
        set{m_to_name=value;}
    }

    public static string To_mail
    {
        set{m_to_mail="<"+value+">";}
    }
    public static string From_name
    {
        set{m_from_name=value;}
    }

    public static string From_mail
    {
        set{m_from_mail="<"+value+">";}
    }

    public static string SmtpServer
    {
        set{smtpServer=value;}
    }

    public static int SmtpPort
    {
        set{smtpPort=value;}
    }

    public static List<string> Mail_body
    {
        set{mail_body=value;}
    }

    public static string Mail_date
    {
        set{m_date=value;}
    }

    private static string m_subject;
    private static string m_to_name;
    private static string m_to_mail;
    private static string m_from_name;
    private static string m_from_mail;
    private static string smtpServer;
    private static string m_date;
    private static int smtpPort;

    private static List<string> mail_body;

    public static void Send()
    {
        // generate an RFC compliant email

        // Заголовок
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("Subject: {0}", m_subject);
        sb.Append(Environment.NewLine);
        sb.AppendFormat("To: {0}{1}", m_to_name, m_to_mail);
        sb.Append(Environment.NewLine);
        sb.AppendFormat("From: {0}{1}", m_from_name, m_from_mail);
        sb.Append(Environment.NewLine);
        //sb.AppendFormat("Date: {0}", DateTime.Now.ToString("ddd, d MMM yyyy H:m:s zz00"));
        sb.AppendFormat("Date: {0}",m_date);
        sb.Append(Environment.NewLine);
        //sb.AppendFormat("Content-Type: text/plain");
        sb.AppendLine("Content-type: text/plain; charset=\"Unicode\"");
        sb.Append(Environment.NewLine);

        //sb.Append(Environment.NewLine);
        // Тело письма
        for(int i=0;i<mail_body.Count;i++)
        {
            sb.Append(mail_body[i]);
            sb.Append(Environment.NewLine);
        }
        sb.Append(Environment.NewLine);

        string email = sb.ToString();

        // Отправка письма с использованием сокета
        ///////////////////////////////////////////

        TcpClient client = null;

        try
        {
            // Установка соединения
            client = new TcpClient(smtpServer, smtpPort);
            NetworkStream ns = client.GetStream();
            StreamReader stdIn  = new StreamReader(ns);
            StreamWriter stdOut = new StreamWriter(ns);

            // Ждем ответа сервера
            int responseCode = GetResponse(stdIn);
            if (responseCode != 220)
                throw new Exception("no smtp server at specified address or smtp server not ready");

            // Посылаем команду HELO
            stdOut.WriteLine("HELO " + Dns.GetHostName());
            stdOut.Flush();
            responseCode = GetResponse(stdIn);
            if (responseCode != 250)
                throw new Exception("helo fails. code="+responseCode);

            // Команда MAIL
            stdOut.WriteLine("MAIL FROM:"+m_from_mail);
            stdOut.Flush();
            responseCode = GetResponse(stdIn);
            if (responseCode != 250)
                throw new Exception("FROM email considered bad by server. code="+responseCode);

            // Команда RCPT 
            stdOut.WriteLine("RCPT TO:"+m_to_mail);
            stdOut.Flush();
            responseCode = GetResponse(stdIn);
            switch(responseCode)
            {
                case 250:
                case 251:
                    break;
                default:
                    throw new Exception("TO email considered bad by server. code="+responseCode);
            }

            // Команда DATA 
            stdOut.WriteLine("DATA");
            stdOut.Flush();
            responseCode = GetResponse(stdIn);
            if (responseCode != 354)
                throw new Exception("data command not accepted. code="+responseCode);

            // Отправка
            stdOut.WriteLine(email);
            stdOut.Flush();

            // Отправка одиночной точки означает завершение отправки
            stdOut.WriteLine(".");
            stdOut.Flush();
            responseCode = GetResponse(stdIn);
            if (responseCode != 250)
                throw new Exception("email not accepted. code="+responseCode);

            // Команда QUIT
            stdOut.WriteLine("QUIT");
            stdOut.Flush();
            responseCode = GetResponse(stdIn);
            if (responseCode != 221)
            {
                //who cares
            }

            MessageBox.Show("Все успешно отправлено");


        }
        catch(Exception ex)
        {
            MessageBox.Show("Ошибка: " + ex.Message);
        }
        finally
        {
            // Закрываем соединение
            if (client != null)
                client.Close();
            client = null;
        }
    }

    static int GetResponse(StreamReader stdIn)
    {
        try
        {
            string response = string.Empty;
            // Читаем ответ сервера
            do
            {
                response += stdIn.ReadLine()+"\r\n";
            }
            while(stdIn.Peek() != -1);

            // Получаем код ответа (первые три символа)
            return Convert.ToInt32(response.Substring(0, 3));
        }
        catch
        {
            // Если ошибка
            return 0;
        }
    }
}

}

3
  • 1
    Зачем вы работаете с почтовиком на таком низком уровне, когда майкрософт представляет пару готовых библиотек со всем необходимым?
    – A K
    24 дек 2018 в 7:13
  • Этот код не будет работать с такими почтовиками как gmail или mail.ru, так как они требуют защищенного соединения, которое включается командой STARTTLS
    – Zergatul
    24 дек 2018 в 11:16
  • автор, ты меня извени, но суть сайта в том чтобы исправлять мои ошибки по данному вопросу, а не делать с нуля новые. В благодарность за потраченное время на меня +1 тебя. Спасибо. 24 дек 2018 в 17:03

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.