243

iPhone アプリケーションからメールを送信したい。iOS SDK には電子メール API がないと聞きました。アプリケーションを終了するため、次のコードは使用したくありません。

NSString *url = [NSString stringWithString: @"mailto:foo@example.com?cc=bar@example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];

では、どうすればアプリからメールを送信できますか?

4

11 に答える 11

429

iOS 3.0 以降では、MessageUI フレームワークに含まれているMFMailComposeViewControllerクラスとプロトコルを使用する必要があります。MFMailComposeViewControllerDelegate

最初にフレームワークを追加してインポートします。

#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
}
于 2009-10-03T10:32:34.790 に答える
61

MFMailComposeViewControllerは、iPhone OS 3.0 ソフトウェアのリリース後に進むべき道です。サンプルコードまたは私が書いたチュートリアルを見ることができます。

于 2009-08-11T02:57:42.940 に答える
20

ここに追加したいことがいくつかあります。

  1. mail.app がシミュレーターにインストールされていないため、mailto URL を使用してもシミュレーターでは機能しません。ただし、デバイス上では動作します。

  2. mailto URL の長さには制限があります。URL が 4096 文字を超える場合、mail.app は起動しません。

  3. OS 3.0 には、アプリを終了せずに電子メールを送信できる新しいクラスがあります。クラス MFMailComposeViewController を参照してください。

于 2009-07-26T20:57:42.460 に答える
13

アプリケーションからメールを送信する場合、アプリ内で独自のメール クライアント (SMTP) をコーディングするか、サーバーにメールを送信させる場合を除き、上記のコードが唯一の方法です。

たとえば、メールを送信するサーバー上の URL を呼び出すようにアプリをコーディングできます。次に、コードから URL を呼び出すだけです。

上記のコードでは、メールに何も添付できないことに注意してください。これは、SMTP クライアント メソッドやサーバー側のメソッドでは可能です。

于 2008-12-23T09:46:35.517 に答える
12

以下のコードは、私のアプリケーションで添付ファイル付きの電子メールを送信するために使用されます。添付ファイルは画像です。任意のタイプのファイルを送信できますが、正しい「mimeType」を指定する必要があることに注意してください。

これを .h ファイルに追加します

#import <MessageUI/MFMailComposeViewController.h>

プロジェクト ファイルにMessageUI.frameworkを追加 します。

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];
}
于 2012-09-21T07:06:04.873 に答える
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:@“&lt;Your Subject Here>”];
    // Set your email body and if body contains HTML then Pass “YES” in isHTML.
    [mailComposer setMessageBody:@“&lt;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;
}
}
于 2016-08-05T13:40:06.107 に答える
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)")

        //------------------------------------------------
    }
}
于 2015-09-22T14:12:46.970 に答える
1

ここにSwiftバージョンがあります:

import MessageUI

class YourVC: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        if MFMailComposeViewController.canSendMail() {
            var emailTitle = "Vea Software Feedback"
            var messageBody = "Vea Software! :) "
            var toRecipents = ["pj@veasoftware.com"]
            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)
    }
}

ソース

于 2015-09-20T11:14:09.443 に答える