免费开源的iOS开发学习平台

系统应用调用:3-发送邮件功能

MFMailComposeViewController简介

在MessageUI框架中,除了提供短信发送功能之外,还提供了邮件发送功能。发送邮件的实现与发送短信类似,只不过需要用到MFMailComposeViewController类,同样可以在不跳出程序的情况下发送邮件。在MFMailComposeViewController类中,包括了如下几个核心的方法和属性。

  • 设置邮件发送对象。recipients是一个数组,因此,可以提供邮件群发功能。
- (void)setToRecipients:(nullable NSArray<NSString *> *)toRecipients;
  • 设置邮件主题
- (void)setSubject:(NSString *)subject;
  • 设置邮件的内容
- (void)setMessageBody:(NSString *)body isHTML:(BOOL)isHTML;
  • 代理对象
 @property (nonatomic, assign, nullable) id<MFMailComposeViewControllerDelegate> mailComposeDelegate;
  • MFMailComposeViewControllerDelegate代理协议中定义了用于邮件发送完成后的回调方法。该代理方法中的result参数会返回邮件发送的结果,其取值包括: MFMailComposeResultSaved(邮件存储)、MFMailComposeResultSent(发送成功)、MFMailComposeResultFailed(发送失败)、MFMailComposeResultCancelled(取消发送)。
- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error;

代码实现

搭建界面,在上一节的基础上,再添加一个【发送邮件】的按钮。

导入头文件,并设置控制器类遵守MFMailComposeViewControllerDelegate协议。

#import "ViewController.h"
#import <MessageUI/MFMailComposeViewController.h>
@interface ViewController ()<MFMailComposeViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end

实现sendMail:方法,实现邮件发送功能。在该方法中创建邮件的收件人、主题以及邮件内容等相关信息。

- (IBAction)sendMail:(id)sender {
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
        controller.mailComposeDelegate = self;
        NSString *recipient = [NSString stringWithFormat:@"%@",self.textField.text];
        [controller setToRecipients:[NSArray arrayWithObjects:recipient, nil]];
        //要发送的邮件主题
        [controller setSubject:@"邮件测试"];
        //要发送邮件的内容
        [controller setMessageBody:@"Hello " isHTML:NO];
        [self presentViewController:controller animated:YES completion:nil];
    }else{
        NSLog(@"设备不具备发送邮件功能");
    }
}

通过MFMailComposeViewControllerDelegate代理协议中的方法,可以获取邮件发送的结果,从而进行后续处理。

- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error {
    if (result == MFMailComposeResultSent) {
        NSLog(@"邮件发送成功");
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

运行效果:

示例代码

https://github.com/99ios/17.6.3