How can I send mail from an iPhone application

2018-12-31 13:56发布

问题:

I want to send an email from my iPhone application. I have heard that the iOS SDK doesn\'t have an email API. I don\'t want to use the following code because it will exit my application:

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]];

So how can I send an email from my app?

回答1:

On iOS 3.0 and later you should use the MFMailComposeViewController class, and the MFMailComposeViewControllerDelegate protocol, that is tucked away in the MessageUI framework.

First add the framework and import:

#import <MessageUI/MFMailComposeViewController.h>

Then, to send a message:

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];

Then the user does the work and you get the delegate callback in time:

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

Remember to check if the device is configured for sending email:

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


回答2:

MFMailComposeViewController is the way to go after the release of iPhone OS 3.0 software. You can look at the sample code or the tutorial I wrote.



回答3:

A few things I\'d like to add here:

  1. Using the mailto URL won\'t work in the simulator as mail.app isn\'t installed on the simulator. It does work on device though.

  2. There is a limit to the length of the mailto URL. If the URL is larger than 4096 characters, mail.app won\'t launch.

  3. There is a new class in OS 3.0 that lets you send an e-mail without leaving your app. See the class MFMailComposeViewController.



回答4:

If you want to send email from your application, the above code is the only way to do it unless you code your own mail client (SMTP) inside your app, or have a server send the mail for you.

For example, you could code your app to invoke a URL on your server which would send the mail for you. Then you simply call the URL from your code.

Note that with the above code you can\'t attach anything to the email, which the SMTP client method would allow you to do, as well as the server-side method.



回答5:

Below code is used in my application to send email with an attachment here the attachments is an image .You can send any type of file only thing is to keep in mind is that you had to specify the correct \'mimeType\'

add this to your .h file

#import <MessageUI/MFMailComposeViewController.h>

Add MessageUI.framework to your project file

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];

Delegate method is as shown below

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


回答6:

This is the code which can help u but dont forget to include message ui framewark and include delegates method 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];
    }


回答7:

To send an email from iPhone application you need to do below list of task.

Step 1: Import #import <MessageUI/MessageUI.h> In your controller class where you want to send an email.

Step 2: Add the delegate to your controller like shown below

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

Step 3: Add below method for send email.

 - (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.
}
}

Step 4: Implement MFMailComposeViewController Delegate

- (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;
}
}


回答8:

Swift 2.2. Adapted from 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)
    }
}

Client code :

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 = [\"foo@bar.com\"]
    ms?.send(title, messageBody: messageBody, toRecipents: toRecipents)
}


回答9:

Swift 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)\")

        //------------------------------------------------
    }
}


回答10:

Heres a Swift version:

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)
    }
}

Source



回答11:

I wrote a simple wrapper called KRNSendEmail that simplify sending email to one method call.

The KRNSendEmail is well documented and added to CocoaPods.

https://github.com/ulian-onua/KRNSendEmail