2016-12-01 1 views
0

Gmail을 사용하여 Xamarin Forms 앱에서 전자 메일을 보내려고합니다.Xamarin.Forms 앱에서 Gmail로부터 전자 메일 보내기

나는 한 가지 방법으로 인터페이스를 만들었습니다 : SendEmail();

그런 다음 Droid 프로젝트에서이 인터페이스를 구현하는 클래스를 추가했습니다. 종속성 속성을 사용하여 메인 프로젝트에서 메소드의 구현을 받고, 모든 다음과 같은 오류를 제외하고 괜찮 :

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("[email protected]"); 
     mail.To.Add("[email protected]"); 
     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의 보안 수준이 낮은 앱 절차를 사용했지만 인증 오류가 발생하지 않아 계정에 제대로 연결될 수 있다고 가정합니다.

답변

0

마침내 자신의 모습을!

우선, 나는 Xamarin의 Android Player를 사용하고 있었는데 분명히 네트워크 연결을 지원하지 않습니다.

Visual Studio Community 2015에 내장 된 Android Emulator (모든 버전)를 사용하고 James Montemagno (Xam.Plugin.Connectivity on NuGet)의 플러그인을 사용하여 네트워크 연결을 테스트했습니다.

2

안녕하세요이 내가이 방법을 사용, 또한 내가 이메일에 파일을 첨부, 아래의 코드를 사용하여 종속성 서비스를 사용하여 얻을 수 있습니다

안드로이드 :

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[] = { "[email protected]" }; 
    //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; 

} 

아이폰 OS를 :

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; 
} 

이 정보가 도움이되기를 바랍니다.

+0

안녕하세요 마리오, 답장을 보내 주셔서 감사합니다! 귀하의 접근 방식이 효과가 있다고 생각하지만, 메일 발신자는 물론 사서함의 로그인을 제어 할 수 있어야합니다. 덜 안전한 Gmail 계정과 Yahoo 계정을 사용해도 위와 같은 오류가 표시됩니다. –