Отправка электронной почты из Gmail в приложении Xamarin.Forms

Я пытаюсь отправить электронное письмо из приложения Xamarin Forms, используя Gmail.

Я создал интерфейс только с 1 методом: SendEmail();

Затем в проекте Droid я добавил класс, который реализует указанный интерфейс. Используя атрибут Dependency и получая реализацию метода в основном проекте, все нормально, кроме следующей ошибки:

Could not resolve host 'smtp.gmail.com'

Это фактическая реализация метода:

    string subject = "subject here ";
    string body= "body here ";
    try
    {
        var mail = new MailMessage();
        var smtpServer = new SmtpClient("smtp.gmail.com", 587);
        mail.From = new MailAddress("myEmailAddress@gmail.com");
        mail.To.Add("anotherAddress@yahoo.com");
        mail.Subject = subject;
        mail.Body = body;
        smtpServer.Credentials = new NetworkCredential("username", "pass");
        smtpServer.UseDefaultCredentials = false;   
        smtpServer.EnableSsl = true;
        smtpServer.Send(mail);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex);

    }

Осматривая вокруг, я не мог найти какие-либо подробности относительно этого, кроме фактического адреса SMTP.

Кроме того, я использовал процедуру менее безопасных приложений от Google, не получая ошибку учетных данных, я предполагаю, что он может подключиться к учетной записи просто отлично.

2 ответа

Решение

Понял, наконец, свой!

Прежде всего, я использовал Android Player от Xamarin, который, очевидно, не поддерживает сетевое подключение.

Поэтому мое решение было простым: использовался эмулятор Android (любая его версия), встроенный в Visual Studio Community 2015, и проверял сетевое подключение с помощью плагина от James Montemagno ( Xam.Plugin.Connectivity на NuGet).

Здравствуйте, я добился этого с помощью кода ниже, также я прикрепил файл к электронной почте, используя службу зависимостей, я использую следующие методы:

Android:

public static string ICSPath
{
    get
    {
        var path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, StaticData.CalendarFolderName);
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        return Path.Combine(path, StaticData.CalendarFileName);
    }
}

public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
    Intent choserIntent = new Intent(Intent.ActionSend);

    //Create the calendar file to attach to the email
    var str = await GlobalMethods.CreateCalendarStringFile(segmentList);

    if (File.Exists(ICSPath))
    {
        File.Delete(ICSPath);
    }

    File.WriteAllText(ICSPath, str);

    Java.IO.File filelocation = new Java.IO.File(ICSPath);
    var path = Android.Net.Uri.FromFile(filelocation);

    // set the type to 'email'
    choserIntent.SetType("vnd.android.cursor.dir/email");
    //String to[] = { "asd@gmail.com" };
    //emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
    // the attachment
    choserIntent.PutExtra(Intent.ExtraStream, path);
    // the mail subject
    choserIntent.PutExtra(Intent.ExtraSubject, "Calendar event");
    Forms.Context.StartActivity(Intent.CreateChooser(choserIntent, "Send Email"));

    return true;

}

IOS:

public static string ICSPath
{
    get
    {
        var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), StaticData.CalendarFolderName);
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        return Path.Combine(path, StaticData.CalendarFileName);
    }
}


public async Task<bool> ShareCalendarEvent(List<ISegment> segmentList)
{
    //Create the calendar file to attach to the email
    var str = await GlobalMethods.CreateCalendarStringFile(segmentList);

    if (File.Exists(ICSPath))
    {
        File.Delete(ICSPath);
    }

    File.WriteAllText(ICSPath, str);

    MFMailComposeViewController mail;
    if (MFMailComposeViewController.CanSendMail)
    {
        mail = new MFMailComposeViewController();
        mail.SetSubject("Calendar Event");
        //mail.SetMessageBody("this is a test", false);
        NSData t_dat = NSData.FromFile(ICSPath);
        string t_fname = Path.GetFileName(ICSPath);
        mail.AddAttachmentData(t_dat, @"text/v-calendar", t_fname);

        mail.Finished += (object s, MFComposeResultEventArgs args) =>
        {
            //Handle action once the email has been sent.
            args.Controller.DismissViewController(true, null);
        };

        Device.BeginInvokeOnMainThread(() =>
        {
            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mail, true, null);
        });

    }
    else
    {
        //Handle not being able to send email
        await App.BasePageReference.DisplayAlert("Mail not supported", 
                                                 StaticData.ServiceUnavailble, StaticData.OK);
    }

    return true;
}

Надеюсь, это поможет.

Другие вопросы по тегам