[英]How to send a mail in Xamarin using System.Net.Mail.SmtpClient
I am trying to send and email for inside an app using system.Net.Mail.SmtpClient. 我正在尝试使用system.Net.Mail.SmtpClient在应用程序内部发送和发送电子邮件。 When I run the code on my phone I get a java.lang.runtimeexception error and I can't figure out why?
当我在手机上运行代码时,出现java.lang.runtimeexception错误,我不知道为什么吗?
I have the following code to run send the email when I click a button. 单击按钮后,我可以运行以下代码来发送电子邮件。
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);
};
}
}
}
Try this it works well for me. 试试这个对我来说很好。 ;)
;)
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.