Home > database >  C# SmtpException - problem with sending mails
C# SmtpException - problem with sending mails

Time:08-16

Sending mails doesn't work. I'm not sure if it's something with client settings or mail server...

When using Gmail SMTP server I got "Connection closed" exception, when changing port to 587 I get "Authentication required" message. What's more interesting when changing SMTP server to something different (smtp.poczta.onet.pl) I get "Time out" exception after ~100s

Here's the code:

protected void SendMessage(object sender, EventArgs e)
{
        // receiver address
        string to = "******@student.uj.edu.pl";

        // mail (sender) address
        string from = "******@gmail.com";

        // SMTP server address
        string server = "smtp.gmail.com";

        // mail password
        string password = "************";

        MailMessage message = new MailMessage(from, to);

        // message title
        message.Subject = TextBox1.Text;

        // message body
        message.Body = TextBox3.Text   " otrzymane "   DateTime.Now.ToString()    " od: "   TextBox2.Text;

        SmtpClient client = new SmtpClient(server, 587);
        client.Credentials = new System.Net.NetworkCredential(from, password);
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.EnableSsl = true;

        try
        {
            client.Send(message);

            // ui confirmation
            TextBox3.Text = "Wysłano wiadmość!";

            // disable button
            Button1.Enabled = false;
        }
        catch (Exception ex)
        {
            // error message
            TextBox3.Text = "Problem z wysłaniem wiadomości ("   ex.ToString()   ")";
        }
 }

I've just read that google don't support some less secure apps (3rd party apps to sign in to Google Account using username and password only) since 30/05/22. Unfortunately can't change it because I have two-stage verification account. Might it be connected? Or is it something with my code?

CodePudding user response:

Gmail doesn't allow, or want you to do that with passwords anymore. They ask you to create a credentials files and then use a token.json to send email.

Using their API from Google.Apis.Gmail.v1 - from Nuget. Here is a method I made and test that is working with gmail.

void Main()
{
    UserCredential credential;

    using (var stream =
        new FileStream(@"C:\credentials.json", FileMode.Open, FileAccess.Read))
    {
        // The file token.json stores the user's access and refresh tokens, and is created
        // automatically when the authorization flow completes for the first time.
        string credPath = "token.json";
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: "   credPath);
    }

    // Create Gmail API service.
    var service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });

    // Define parameters of request.
    UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");

    // List labels.
    IList<Label> labels = request.Execute().Labels;
    Console.WriteLine("Labels:");
    if (labels != null && labels.Count > 0)
    {
        foreach (var labelItem in labels)
        {
            Console.WriteLine("{0}", labelItem.Name);
        }
    }
    else
    {
        Console.WriteLine("No labels found.");
    }
    //Console.Read();
    var msg = new Google.Apis.Gmail.v1.Data.Message();
    MimeMessage message = new MimeMessage();
    
    message.To.Add(new MailboxAddress("", "toemail.com"));
    message.From.Add(new MailboxAddress("Some Name", "[email protected]"));
    message.Subject = "Test email with Mime Message";
    message.Body = new TextPart("html") {Text = "<h1>This</h1> is a body..."};
    
    var ms = new MemoryStream();
    message.WriteTo(ms);
    ms.Position = 0;
    StreamReader sr = new StreamReader(ms);
    string rawString = sr.ReadToEnd();

    byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
    msg.Raw = System.Convert.ToBase64String(raw);
    
    var res = service.Users.Messages.Send(msg, "me").Execute();
    
    res.Dump();


}
static string[] Scopes = { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels, GmailService.Scope.GmailCompose, GmailService.Scope.MailGoogleCom};
static string ApplicationName = "Gmail API Send Email";

CodePudding user response:

Enable 2FA on your email and generate a password for your application using the link. As far as I know, login and password authorization using unauthorized developer programs is no longer supported by Google.

CodePudding user response:

Can you ping the smpt server from your machine or the machine you deploy the code from? THis could be a DNS issue.

  • Related