programing

iPhone 응용 프로그램에서 메일을 보내는 방법

minimums 2023. 5. 18. 20:53
반응형

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

그럼 어떻게 앱에서 이메일을 보낼 수 있나요?

iOS 3.0 이상에서는 다음을 사용해야 합니다.MFMailComposeViewController클래스, 그리고MFMailComposeViewControllerDelegate메시지에 들어 있는 프로토콜UI 프레임워크.

먼저 프레임워크를 추가하고 다음을 가져옵니다.

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

MFMailComposeViewController는 iPhone OS 3.0 소프트웨어 릴리스 이후에 사용할 수 있는 방법입니다.샘플 코드나 가 작성한 튜토리얼을 보시면 됩니다.

여기에 몇 가지 추가하고 싶은 것이 있습니다.

  1. 시뮬레이터에 mail.app이 설치되어 있지 않기 때문에 메일을 URL로 보내는 것은 시뮬레이터에서 작동하지 않습니다.하지만 장치에서 작동합니다.

  2. URL에 대한 메일 길이에 제한이 있습니다.URL이 4096자보다 크면 mail.app이 실행되지 않습니다.

  3. OS 3.0에는 앱을 떠나지 않고 이메일을 보낼 수 있는 새로운 클래스가 있습니다.MFMailComposeViewController 클래스를 참조하십시오.

응용 프로그램에서 전자 메일을 보내려면 응용 프로그램 내에서 사용자의 SMTP(메일 클라이언트)를 코딩하거나 서버에서 메일을 보내도록 하지 않는 한 위의 코드가 유일한 방법입니다.

예를 들어, 사용자 대신 메일을 보내는 서버의 URL을 호출하도록 앱을 코딩할 수 있습니다.그런 다음 코드에서 URL을 부르기만 하면 됩니다.

위의 코드를 사용하면 SMTP 클라이언트 방법과 서버 측 방법을 사용할 수 있는 전자 메일에 첨부할 수 없습니다.

아래 코드는 첨부파일이 있는 이메일을 보낼 때 제 애플리케이션에서 사용됩니다. 첨부파일은 이미지입니다.모든 유형의 파일을 보낼 수 있습니다. 주의해야 할 점은 올바른 'mime'을 지정해야 한다는 것입니다.유형'

.h 파일에 추가합니다.

#import <MessageUI/MFMailComposeViewController.h>

메시지 추가프로젝트 파일의 UI.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];
}

이 코드는 도움이 될 수 있지만 메시지 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];
    }

스위프트 2.2.Esq의 답변을 바탕으로 수정됨

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

iPhone 응용 프로그램에서 이메일을 보내려면 아래 작업 목록을 수행해야 합니다.

1단계: 이메일을 보낼 컨트롤러 클래스에서 가져오기.

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단계: MFMail ComposeView 컨트롤러 위임 구현

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

스위프트 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)")

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

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

원천

저는 KRNsendEmail이라는 간단한 포장지를 작성하여 이메일을 한 번의 메소드 호출로 전송하는 것을 단순화했습니다.

KRN Send Email은 잘 문서화되어 있으며 코코아 포드에 추가되어 있습니다.

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

언급URL : https://stackoverflow.com/questions/310946/how-can-i-send-mail-from-an-iphone-application

반응형

'programing' 카테고리의 다른 글

메이븐 인 이클립스: 단계별 설치  (0) 2023.05.18
Spring MongoDB 쿼리 정렬  (0) 2023.05.18
설정이 다른 두 파일에 로깅  (0) 2023.05.18
Bash 명령줄 및 입력 제한  (0) 2023.05.18
코드 파일 대 코드 이면  (0) 2023.05.18