Home > OS >  Gmail email send c#
Gmail email send c#

Time:06-17

This code works when i try send message to this same email but on other, don't works without error

        var smtpClient = new SmtpClient("smtp.gmail.com")
        {
            Port = 587,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential("[email protected]", "myapppass"),
            EnableSsl = true,
        };

        smtpClient.Send("[email protected]", "email", "Authorization!", "body");

CodePudding user response:

Try formatting the message as I have here. and use Authenticate instead of NetworkCredential.

using MailKit.Net.Smtp;
using MimeKit;

Console.WriteLine("Hello, World!");

var message = new EmailMessage()
{
    From = "[email protected]",
    To = "[email protected]",
    MessageText = "test",
    Subject = "test"
};

try
{
    using (var client = new SmtpClient())
    {
        client.Connect("smtp.gmail.com", 465, true);
        client.Authenticate(message.From, "AppsPassword");
        client.Send(message.GetMessage());
        client.Disconnect(true);
    }

   
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}


public class EmailMessage
{
    public string To { get; set; }
    public string From { get; set; }
    public string Subject { get; set; }
    public string MessageText { get; set; }

    public MimeMessage GetMessage()
    {
        var body = MessageText;
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("test", From));
        message.To.Add(new MailboxAddress("test", To));
        message.Subject = Subject;
        message.Body = new TextPart("plain") { Text = body };
        return message;
    }
}
  • Related