IOS开发中发送Email的两种方法



  1. 1、使用openURL来实现发邮件的功能:
  2. NSString *url = [NSStringstringWithString: 
  3. @"mailto:foo@example.com?cc=bar@example.com&subject=Greetings from Cupertino!& body=Wish youwere here!"];
  4. [[UIApplicationsharedApplication] 
  5. openURL: [NSURLURLWithString: url]];

  6. 缺点很明显,这样的过程会导致程序暂时退出,即使在iOS4.x支持多任务的情况下,这样的过程还是会让人觉得不是很方便。

  7. 2、使用MFMailComposeViewController来实现发邮件的功能,它在MessageUI.framework中,你需要在项目中加入该框架,并在使用的文件中导入MFMailComposeViewController.h头文件。
  8. #import ;

  9. MFMailComposeViewController* 
  10. controller =[[MFMailComposeViewController alloc] init];
  11. controller.mailComposeDelegate = self;
  12. [controller setSubject:@"MySubject"];
  13. [controllersetMessageBody:@"Hello there." isHTML:NO];
  14. [selfpresentModalViewController:controller animated:YES];
  15. [controllerrelease];

  16. 使用该方法实现发送Email是最常规的方法,该方法有相应的MFMailComposeViewControllerDelegate事件:
  17. -(void)mailComposeController:(MFMailComposeViewController*)controller
  18.        didFinishWithResult:(MFMailComposeResult)result
  19.                 error:(NSError*)error;
  20. {
  21.   if (result ==MFMailComposeResultSent) {
  22.    NSLog(@"It's away!");
  23.   }
  24.   [selfdismissModalViewControllerAnimated:YES];
  25. }

  26. 有一些相关的数据结构的定义在头文件中都有具体的描述:
  27. enum MFMailComposeResult{
  28.   MFMailComposeResultCancelled,//用户取消编辑邮件
  29.    MFMailComposeResultSaved,//用户成功保存邮件
  30.   MFMailComposeResultSent,//用户点击发送,将邮件放到队列中
  31.   MFMailComposeResultFailed//用户试图保存或者发送邮件失败
  32. };
  33. typedef enumMFMailComposeResult MFMailComposeResult;  
  34. // iOS3.0以上有效

  35. 在头文件中MFMailComposeViewController的部分方法顺便提及:
  36. + (BOOL)canSendMail__OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
  37. //如果用户没有设置邮件账户,则会返回NO,你可以用根据返回值来决定是  使用MFMailComposeViewController  还是mailto://的传统方法,也或者,  你可以选择上文中提到的skpsmtpmessage来实现发送Email的功能。
  38. -(void)addAttachmentData:(NSData*)attachment 
  39. mimeType:(NSString*)mimeType fileName:(NSString *)filename;
  40. //NSData类型的attachment自然不必多说,关于mimeType需要一点说明,  官方文档里给出了一个链接[url]http://www.iana.org/assignments/media-types/[/url],   这里列出的所有的类型都应该支持。关于mimeType的用处,更多需要依靠搜索引擎了 =]

  41. 第二种方法的劣势也很明显,iOS系统替我们提供了一个mail中的UI,而我们却完全无法对齐进行订制,这会让那些定制化成自己风格的App望而却步,因为这样使用的话无疑太突兀了。


  42. 3、我们可以根据自己的UI设计需求来定制相应的视图以适应整体的设计。可以使用比较有名的开源SMTP协议来实现。


  43. 在SKPSMTPMessage类中,并没有对视图进行任何的要求,它提供的都是数据层级的处理,你之需要定义好相应的发送要求就可以实现邮件发送了。至于是以什么样的方式获取这些信息,就可以根据软件的需求来确定交互方式和视图样式了。


  44.   SKPSMTPMessage *testMsg =[[SKPSMTPMessage alloc] init];
  45.              testMsg.fromEmail = @"test@gmail.com";
  46.              testMsg.toEmail =@"to@gmail.com";
  47.              testMsg.relayHost = @"smtp.gmail.com";
  48.              testMsg.requiresAuth = YES;
  49.              testMsg.login = @"test@gmail.com";
  50.              testMsg.pass = @"test";
  51.              testMsg.subject = [NSStringstringWithCString:"测试" encoding:NSUTF8StringEncoding];
  52.              testMsg.bccEmail = @"bcc@gmail.com";
  53.              testMsg.wantsSecure = YES; // smtp.gmail.comdoesn't work without TLS!

  54.              // Only do this for self-signed certs!
  55.              // testMsg.validateSSLChain = NO;
  56.              testMsg.delegate = self;

  57. NSDictionary *plainPart =[NSDictionary 
  58. dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,
  59. [NSStringstringWithCString:"测试正文" encoding:NSUTF8StringEncoding],
  60. kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];

  61. NSString *vcfPath =[[NSBundle mainBundle] pathForResource:@"test"ofType:@"vcf"];
  62. NSData *vcfData = [NSDatadataWithContentsOfFile:vcfPath];

  63. NSDictionary *vcfPart =[NSDictionary dictionaryWithObjectsAndKeys:@"text/directory;rntx-unix-mode=0644;rntname="test.vcf"",kSKPSMTPPartContentTypeKey,
  64. @"attachment;rntfilename="test.vcf"",kSKPSMTPPartContentDispositionKey,
  65. [vcfDataencodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
  66. testMsg.parts = [NSArrayarrayWithObjects:plainPart,vcfPart,nil];
  67. [testMsg send];



  68. 该类也提供了相应的Delegate方法来让你更好的获知发送的状态.
  69. -(void)messageSent:(SKPSMTPMessage *)message;
  70. -(void)messageFailed:(SKPSMTPMessage*)message 
  71. error:(NSError*)error;

实例:

1.首先添加 MessageUI.framework 框架

2. 引入框架

  在类的头部

  #import <MessageUI/MessageUI.h>

  #import <MessageUI/MFMailComposeViewController.h>

3. 实现接口 

  <MFMailComposeViewControllerDelegate>

4.  当点击一个button 跳转到发邮件的页面 调用我们发邮件 

发邮件是有两种方式 :

1. 当你的设备支持的时候 the current device is configured for sending emails

    我们使用一下的tool methods 中的displayComposerSheet 方法来发送邮件(其中使用了apple 集成好的 邮件picker --         MFMailComposeViewController) 在这里 我们将这个picker 看做是一个  模式视图 ModalViewController 推出了 

2. 当设备不支持的时候 我们采用  

launchMailAppOnDevice 方法发送 ( 采用打开一个url地址的 方式来发)  ok..

-----点击按钮出发的方法

- (IBAction)contactBtnPressed:(id)sender {

    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));

if (mailClass != nil)

{

// We must always check whether the current device is configured for sending emails

if ([mailClass canSendMail])

{

[self displayComposerSheet];

}

else

{

[selflaunchMailAppOnDevice];

}

}

else

{

[selflaunchMailAppOnDevice];

}

}

----- tool Methods 工具方法

 

// 1.  Launches the Mail application on the device.

-(void)launchMailAppOnDevice

{

NSString *recipients = @"mailto:maxwellsoftware@gmail.com&subject=Pocket Truth or Dare Support";

NSString *body = @"&body=email body!";

NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];

email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[[UIApplicationsharedApplicationopenURL:[NSURLURLWithString:email]];

}

 

// 2. Displays an email composition interface inside the application. Populates all the Mail fields. 

-(void)displayComposerSheet 

{

    MFMailComposeViewController *picker = [[MFMailComposeViewControllerallocinit];/*MFMailComposeViewController邮件发送选择器*/

picker.mailComposeDelegate = self;

    [picker setSubject:@"Pocket Truth or Dare Support"];/*emailpicker标题题行*/

    

    // Custom NavgationBar background And set the backgroup picture

    picker.navigationBar.tintColor = [UIColorcolorWithRed:209.0/255green:183.0/255blue:126.0/255alpha:1.0];

 

    //    picker.navigationBar.tintColor = [UIColor colorWithRed:178.0/255 green:173.0/255 blue:170.0/255 alpha:1.0];

    

    if ([[[UIDevicecurrentDevicesystemVersionfloatValue] >= 5.0) {

        [picker.navigationBarsetBackgroundImage:[UIImageimageNamed:@"nav_bg.png"]forBarMetrics:UIBarMetricsDefault];

    }

    

// Set up recipients

NSArray *toRecipients = [NSArrayarrayWithObject:@"maxwellsoftware@gmail.com"]; 

 

[picker setToRecipients:toRecipients];

 

// Fill out the email body text

    struct utsname device_info;

 

    uname(&device_info);

    NSString *emailBody = [NSString 

            stringWithFormat:@"Model: %s\nVersion: %@\nApp: %@\nFeedback here:\n",device_info.machine,

            [[UIDevicecurrentDevicesystemVersion],/*设备系统环境*/

            [[[NSBundlemainBundleinfoDictionary]

             objectForKey:@"CFBundleShortVersionString"]];/**/

    

    NSLog(@"ios 应用发布后 .app 应用文件路径::%@",[NSBundle mainBundle] );

    NSLog(@"ios 应用发布后 .app 应用文件 ::%@",[[NSBundle mainBundle] infoDictionary]);

    

[picker setMessageBody:emailBody isHTML:NO];

   

[selfpresentModalViewController:picker animated:YES];

    [picker release];

}

 

// 3. 一个备用的方法

//- (void) alertWithTitle: (NSString *)_title_ msg: (NSString *)msg   

//{  

//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_title_   

//                                                    message:msg   

//                                                   delegate:nil   

//                                          cancelButtonTitle:@"Sure"   

//                                          otherButtonTitles:nil];  

//    [alert show];  

//    [alert release];

//}

----协议的委托方法

 

// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 

{

//    NSString *title = @"Mail";

//    NSString *msg;

//    switch (result)  

//    {  

//        case MFMailComposeResultCancelled:  

//            msg = @"Mail canceled";//@"邮件发送取消";  

//            break;  

//        case MFMailComposeResultSaved:  

//            msg = @"Mail saved";//@"邮件保存成功";  

//            [self alertWithTitle:title msg:msg];  

//            break;  

//        case MFMailComposeResultSent:  

//            msg = @"Mail sent";//@"邮件发送成功";  

//            [self alertWithTitle:title msg:msg];  

//            break;  

//        case MFMailComposeResultFailed:  

//            msg = @"Mail failed";//@"邮件发送失败";  

//            [self alertWithTitle:title msg:msg];  

//            break;  

//        default: 

//            msg = @"Mail not sent";

//            [self alertWithTitle:title msg:msg];

//            break;  

//    }  

[self  dismissModalViewControllerAnimated:YES];

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值