2008-11-22 81 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; 
} 
} 
相关问题