如何使用System.Net.Mail.SmtpClient在Xamarin中发送邮件

时间:2015-05-15 09:18:27

标签: c# android email xamarin smtpclient

我正在尝试使用system.Net.Mail.SmtpClient在应用内发送和发送电子邮件。当我在手机上运行代码时,我收到java.lang.runtimeexception错误,我无法弄清楚原因?

我有以下代码可以在点击按钮时发送电子邮件。

using System;
using Android.App;
using Android.Widget;
using Android.OS;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;

namespace SendEmail
{
[Activity (Label = "SendEmail", MainLauncher = true)]
public class Activity1 : Activity
{

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        Button button = FindViewById<Button> (Resource.Id.myButton);
        EditText Text = FindViewById<EditText> (Resource.Id.MailText);

        button.Click += delegate {

             string username = "****@gmail.com";
             string password = "****";
             System.Net.NetworkCredential nc = new
             System.Net.NetworkCredential(username, password);
             MailMessage MailMessage = new MailMessage();
             MailMessage.To.Add("****@gmail.com");
             MailMessage.Subject = "here is the subject";
             MailMessage.From = new System.Net.Mail.MailAddress("****@gmail.com");
             MailMessage.Body = "Application run time was ";
             System.Net.Mail.SmtpClient SmtpClient = new System.Net.Mail.SmtpClient("smtp.gmail.com");
                 SmtpClient.UseDefaultCredentials = false;

                 SmtpClient.EnableSsl = true;
                 SmtpClient.Credentials = nc;
                 SmtpClient.Port = 587;
            SmtpClient.Send(MailMessage);

        };
     }
}
}

1 个答案:

答案 0 :(得分:6)

试试这个对我来说效果很好。 ;)

    try
    {
        MailMessage mail=new MailMessage();
        SmtpClient SmtpServer=new SmtpClient("smtp.gmail.com");
        mail.From=new MailAddress("from address here");
        mail.To.Add("to adress here");
        mail.Subject = "Message Subject";
        mail.Body = "Message Body";
        SmtpServer.Port = 587;
        SmtpServer.Credentials=new System.Net.NetworkCredential("username","password");
        SmtpServer.EnableSsl=true;
        ServicePointManager.ServerCertificateValidationCallback=delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) {
            return true;
        };
        SmtpServer.Send(mail);
        Toast.MakeText(Application.Context, "Mail Send Sucessufully", ToastLength.Short).Show();
    }

     catch(Exception ex) 
     {
         Toast.MakeText(Application.Context,ex.ToString(),ToastLength.Long);
     }