无法使用来自xamarin.android应用程序的Mailkit发送电子邮件

时间:2017-08-03 16:16:18

标签: c# xamarin xamarin.android mailkit

我无法使用jstedfastMailKit库从xamarin.android应用发送电子邮件。

我使用以下代码:

try
{
    //From Address
    string FromAddress = "from_sender@gmail.com";
    string FromAdressTitle = "Email Title";
    //To Address
    string ToAddress = "to_receiver@gmail.com";
    string ToAdressTitle = "Address Title";
    string Subject = "Subject of mail";
    string BodyContent = "Body of email";

    //Smtp Server
    string SmtpServer = "smtp.gmail.com";
    //Smtp Port Number
    int SmtpPortNumber = 587;

    var mimeMessage = new MimeMessage();
    mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
    mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
    mimeMessage.Subject = Subject;
    mimeMessage.Body = new TextPart("plain")
    {
        Text = BodyContent

    };

    using (var client = new SmtpClient())
    {

        client.Connect(SmtpServer, SmtpPortNumber, false);
        // Note: only needed if the SMTP server requires authentication
        // Error 5.5.1 Authentication 
        client.AuthenticationMechanisms.Remove("XOAUTH2");
        client.Authenticate("from_sender@gmail.com", "password");
        client.Send(mimeMessage);
        Console.WriteLine("The mail has been sent successfully !!");
        Console.ReadLine();
        client.Disconnect(true);

    }

}
catch (Exception ex) 
{
    string message = ex.Message;
}

当我从我的应用程序运行此代码时,它会引发异常:

  

MailKit.Security.AuthenticationException

enter image description here

此代码中缺少的内容。任何人都可以帮助我!

1 个答案:

答案 0 :(得分:1)

使用MAILMESSAGE类。

using System.Net.Mail;

MailMessage mail = new MailMessage("example@gmail.com", "example@gmail.com", "Title","Body");
                    SmtpClient client = new SmtpClient();
                    client.Host = ("smtp.gmail.com");
                    client.Port = 587; //smtp port for SSL
                    client.Credentials = new System.Net.NetworkCredential("example@gmail.com", "password");
                    client.EnableSsl = true; //for gmail SSL must be true

                    client.Send(mail);