iOS - 傳送電子郵箱(Email)


簡介

我們可以使用電子郵件應用程式 iOS 裝置傳送電子郵件(Email)。

 

涉及的步驟

1. 建立一個簡單的 View based application.

2. 選擇專案檔案,然後選擇目標,新增 MessageUI.framework.

3. 在 ViewController.xib 新增一個按鍵並建立一個用於傳送電子郵件的動作。

 

4. 更新 ViewController.h 如下

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>

@interface ViewController : UIViewController<MFMailComposeViewControllerDelegate>
{
    MFMailComposeViewController *mailComposer;
}

-(IBAction)sendMail:(id)sender;

@end

4. 更新 ViewController.m 如下

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];   
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)sendMail:(id)sender{
    mailComposer = [[MFMailComposeViewController alloc]init];
    mailComposer.mailComposeDelegate = self;
    [mailComposer setSubject:@"Test mail"];
    [mailComposer setMessageBody:@"Testing message 
    for the test mail" isHTML:NO];
    [self presentModalViewController:mailComposer animated:YES];
}

#pragma mark - mail compose delegate
-(void)mailComposeController:(MFMailComposeViewController *)controller 
 didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
   if (result) {
        NSLog(@"Result : %d",result);
    }
    if (error) {
        NSLog(@"Error : %@",error);
    }
    [self dismissModalViewControllerAnimated:YES];

}

@end

輸出

現在,當我們執行程式時,我們會得到下面的輸出。

iOS Tutorial

在點選“傳送電子郵件,我們將得到下面的輸出。

iOS Tutorial