2008-11-22 77 views
242

我想從我的iPhone應用程序發送電子郵件。我聽說iOS SDK沒有電子郵件API。我不想使用下面的代碼,因爲這將退出我的應用程序:如何從iPhone應用程序發送郵件

NSString *url = [NSString stringWithString: @"mailto:[email protected][email protected]&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"]; 
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]]; 

那麼,怎樣才能從我的應用程序發送電子郵件?

回答

13

如果你想從你的應用程序發送的電子郵件,上面的代碼是做它,除非你你的應用程序中編寫自己的郵件客戶端(SMTP),或有一臺服務器發送郵件給你的唯一途徑。

例如,您可以編寫您的應用程序來調用服務器上的URL,以便爲您發送郵件。然後你只需從你的代碼中調用URL。

注意,與上面的代碼,你可以不要將任何東西的電子郵件,這SMTP客戶端方法將允許你這樣做,以及服務器端的方法。

19

有幾件事情,我想在這裏補充:

  1. 使用的mailto URL作爲mail.app沒有在模擬器上安裝模擬器將無法正常工作。它確實在設備上工作。

  2. 有到的mailto URL的長度的限制。如果URL大於4096個字符,則mail.app不會啓動。

  3. 有一個在OS 3.0的新類,讓您無需離開應用程序發送電子郵件。請參閱MFMailComposeViewController類。

61

MFMailComposeViewController是iPhone OS 3.0軟件發佈之後的方式。您可以查看sample codetutorial I wrote

+2

Mugunth的真棒帖子。去哥們的路! – Jordan 2009-08-20 23:46:00

+1

它真的很棒。謝謝。 我設計了一個專門用於接受來自用戶的電子郵件和主題的視圖。通過執行相同的代碼,它再次顯示了相似的觀點。我可以從我的按鈕按下事件在視圖控制器類調用的委託方法 感謝您的幫助, 世斌 – smakstr 2010-04-29 12:07:54

+0

我已經下載了相同的示例代碼,但它不發送任何郵件。它只提示郵件發送成功,但沒有收到郵件。我試過添加默認顯示爲紅色的MessageUI框架,但應用程序仍然沒有發送郵件。任何在這方面的幫助將不勝感激。我正在模擬器中測試該應用程序。 – 2010-12-10 14:07:23

431

在iOS 3.0及更高版本中,您應該使用隱藏在MessageUI框架中的MFMailComposeViewController類和MFMailComposeViewControllerDelegate協議。

首先添加framework和進口:

#import <MessageUI/MFMailComposeViewController.h> 

然後發送消息:

MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init]; 
controller.mailComposeDelegate = self; 
[controller setSubject:@"My Subject"]; 
[controller setMessageBody:@"Hello there." isHTML:NO]; 
if (controller) [self presentModalViewController:controller animated:YES]; 
[controller release]; 

然後用戶做的工作,你會得到及時委託回調:

- (void)mailComposeController:(MFMailComposeViewController*)controller 
      didFinishWithResult:(MFMailComposeResult)result 
         error:(NSError*)error; 
{ 
    if (result == MFMailComposeResultSent) { 
    NSLog(@"It's away!"); 
    } 
    [self dismissModalViewControllerAnimated:YES]; 
} 

注意檢查設備配置爲發送電子郵件:

if ([MFMailComposeViewController canSendMail]) { 
    // Show the composer 
} else { 
    // Handle the error 
} 
12

下面的代碼在我的應用程序用於與這裏的附件的附件發送電子郵件是一個圖像。您可以發送任何類型的文件的唯一的事情是要記住的是,你必須指定正確的'mime類型'

添加到您的.h文件中

#import <MessageUI/MFMailComposeViewController.h> 

添加MessageUI。框架到您的項目文件

NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 

NSString *documentsDirectory = [paths objectAtIndex:0]; 

NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"myGreenCard.png"]; 



MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init]; 
controller.mailComposeDelegate = self; 
[controller setSubject:@"Green card application"]; 
[controller setMessageBody:@"Hi , <br/> This is my new latest designed green card." isHTML:YES]; 
[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@"png" fileName:@"My Green Card"]; 
if (controller) 
    [self presentModalViewController:controller animated:YES]; 
[controller release]; 

委託方法如下圖所示

-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error; 
{ 
    if (result == MFMailComposeResultSent) { 
     NSLog(@"It's away!"); 
    } 
    [self dismissModalViewControllerAnimated:YES]; 
} 
11

這是代碼,可以幫助ü,但不要忘了,包括消息UI framewark,包括代表法MFMailComposeViewControllerDelegate

-(void)EmailButtonACtion{ 

     if ([MFMailComposeViewController canSendMail]) 
     { 
      MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init]; 
      controller.mailComposeDelegate = self; 
      [controller.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigation_bg_iPhone.png"] forBarMetrics:UIBarMetricsDefault]; 
      controller.navigationBar.tintColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0]; 
      [controller setSubject:@""]; 
      [controller setMessageBody:@" " isHTML:YES]; 
      [controller setToRecipients:[NSArray arrayWithObjects:@"",nil]]; 
      UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; 
      UIImage *ui = resultimg.image; 
      pasteboard.image = ui; 
      NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(ui)]; 
      [controller addAttachmentData:imageData mimeType:@"image/png" fileName:@" "]; 
      [self presentViewController:controller animated:YES completion:NULL]; 
     } 
     else{ 
      UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"alrt" message:nil delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil] ; 
      [alert show]; 
     } 

    } 
    -(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
    { 

     [MailAlert show]; 
     switch (result) 
     { 
      case MFMailComposeResultCancelled: 
       MailAlert.message = @"Email Cancelled"; 
       break; 
      case MFMailComposeResultSaved: 
       MailAlert.message = @"Email Saved"; 
       break; 
      case MFMailComposeResultSent: 
       MailAlert.message = @"Email Sent"; 
       break; 
      case MFMailComposeResultFailed: 
       MailAlert.message = @"Email Failed"; 
       break; 
      default: 
       MailAlert.message = @"Email Not Sent"; 
       break; 
     } 
     [self dismissViewControllerAnimated:YES completion:NULL]; 
     [MailAlert show]; 
    } 
1

繼承人一個迅捷版本:

import MessageUI 

class YourVC: UIViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     if MFMailComposeViewController.canSendMail() { 
      var emailTitle = "Vea Software Feedback" 
      var messageBody = "Vea Software! :) " 
      var toRecipents = ["[email protected]"] 
      var mc:MFMailComposeViewController = MFMailComposeViewController() 
      mc.mailComposeDelegate = self 
      mc.setSubject(emailTitle) 
      mc.setMessageBody(messageBody, isHTML: false) 
      mc.setToRecipients(toRecipents) 
      self.presentViewController(mc, animated: true, completion: nil) 
     } else { 
      println("No email account found") 
     } 
    } 
} 

extension YourVC: MFMailComposeViewControllerDelegate { 
    func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { 
     switch result.value { 
     case MFMailComposeResultCancelled.value: 
      println("Mail Cancelled") 
     case MFMailComposeResultSaved.value: 
      println("Mail Saved") 
     case MFMailComposeResultSent.value: 
      println("Mail Sent") 
     case MFMailComposeResultFailed.value: 
      println("Mail Failed") 
     default: 
      break 
     } 
     self.dismissViewControllerAnimated(false, completion: nil) 
    } 
} 

Source

2

夫特2.0

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?){ 
    if let error = error{ 
     print("Error: \(error)") 
    }else{ 
     //NO Error 
     //------------------------------------------------ 
     var feedbackMsg = "" 

     switch result.rawValue { 
     case MFMailComposeResultCancelled.rawValue: 
      feedbackMsg = "Mail Cancelled" 
     case MFMailComposeResultSaved.rawValue: 
      feedbackMsg = "Mail Saved" 
     case MFMailComposeResultSent.rawValue: 
      feedbackMsg = "Mail Sent" 
     case MFMailComposeResultFailed.rawValue: 
      feedbackMsg = "Mail Failed" 
     default: 
      feedbackMsg = "" 
     } 

     print("Mail: \(feedbackMsg)") 

     //------------------------------------------------ 
    } 
} 
2

夫特2.2。從Esq's answer

import Foundation 
import MessageUI 

class MailSender: NSObject, MFMailComposeViewControllerDelegate { 

    let parentVC: UIViewController 

    init(parentVC: UIViewController) { 
     self.parentVC = parentVC 
     super.init() 
    } 

    func send(title: String, messageBody: String, toRecipients: [String]) { 
     if MFMailComposeViewController.canSendMail() { 
      let mc: MFMailComposeViewController = MFMailComposeViewController() 
      mc.mailComposeDelegate = self 
      mc.setSubject(title) 
      mc.setMessageBody(messageBody, isHTML: false) 
      mc.setToRecipients(toRecipients) 
      parentVC.presentViewController(mc, animated: true, completion: nil) 
     } else { 
      print("No email account found.") 
     } 
    } 

    func mailComposeController(controller: MFMailComposeViewController, 
     didFinishWithResult result: MFMailComposeResult, error: NSError?) { 

      switch result.rawValue { 
      case MFMailComposeResultCancelled.rawValue: print("Mail Cancelled") 
      case MFMailComposeResultSaved.rawValue: print("Mail Saved") 
      case MFMailComposeResultSent.rawValue: print("Mail Sent") 
      case MFMailComposeResultFailed.rawValue: print("Mail Failed") 
      default: break 
      } 

      parentVC.dismissViewControllerAnimated(false, completion: nil) 
    } 
} 

客戶端代碼改編:

var ms: MailSender? 

@IBAction func onSendPressed(sender: AnyObject) { 
    ms = MailSender(parentVC: self) 
    let title = "Title" 
    let messageBody = "https://stackoverflow.com/questions/310946/how-can-i-send-mail-from-an-iphone-application this question." 
    let toRecipents = ["[email protected]"] 
    ms?.send(title, messageBody: messageBody, toRecipents: toRecipents) 
} 
4

要發送的iPhone應用程序,你需要做下面的任務列表中的郵件。

第1步:導入#import <MessageUI/MessageUI.h>在您想要發送電子郵件的控制器類中。

第2步:委託添加到您的控制器像圖所示

@interface <yourControllerName> : UIViewController <MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate> 

3步:添加以下方法發送電子郵件。

- (void) sendEmail { 
// Check if your app support the email. 
if ([MFMailComposeViewController canSendMail]) { 
    // Create an object of mail composer. 
    MFMailComposeViewController *mailComposer =  [[MFMailComposeViewController alloc] init]; 
    // Add delegate to your self. 
    mailComposer.mailComposeDelegate = self; 
    // Add recipients to mail if you do not want to add default recipient then remove below line. 
    [mailComposer setToRecipients:@[<add here your recipient objects>]]; 
    // Write email subject. 
    [mailComposer setSubject:@「<Your Subject Here>」]; 
    // Set your email body and if body contains HTML then Pass 「YES」 in isHTML. 
    [mailComposer setMessageBody:@「<Your Message Body>」 isHTML:NO]; 
    // Show your mail composer. 
    [self presentViewController:mailComposer animated:YES completion:NULL]; 
} 
else { 
// Here you can show toast to user about not support to sending email. 
} 
} 

第4步:實施MFMailComposeViewController代表

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(nullable NSError *)error { 
[controller dismissViewControllerAnimated:TRUE completion:nil]; 


switch (result) { 
    case MFMailComposeResultSaved: { 
    // Add code on save mail to draft. 
    break; 
} 
case MFMailComposeResultSent: { 
    // Add code on sent a mail. 
    break; 
} 
case MFMailComposeResultCancelled: { 
    // Add code on cancel a mail. 
    break; 
} 
case MFMailComposeResultFailed: { 
    // Add code on failed to send a mail. 
    break; 
} 
default: 
    break; 
} 
} 
相關問題