iOS Development-Send email (e-mail) method to organize the collection (total 3 kinds)

Source: Internet
Author: User
Tags email account mail account

In the development of iOS, sometimes we need to use the function of mail sending. For example, receive user feedback and program crash notifications, and so on. In fact, this feature is very common, because I currently have to send email development needs, so by the way to organize the way iOS send mail.

iOS native comes with two ways to send mail, and the other is to use a third-party library:

1) openURL (native)

-The user experience is poor, the program will go backstage and jump to the mail sending interface.

2) mfmailcomposeviewcontroller (native)

--does not enter the background and uses modal pop-up messages to send views.

3) skpsmtpmessage (https://github.com/jetseven/skpsmtpmessage)

--You don't have to tell the user what's going to happen, I wonder if this is not the apple theory. Of course you can also get a popup box to inform the user before sending, and let the user choose whether to send.

The following code is tested on the real machine (IOS8.0) and passed the test.

First, using OpenURL to send mail:

Create a variable address string object:

nsmutablestring *mailurl = [[Nsmutablestring alloc] init];

To add a recipient:

Nsarray *torecipients = @[@ "Write your own mailbox test @qq. com"]; // Note: If there are multiple recipients, you can use the Componentsjoinedbystring method to connect, the connector is @ "," [Mailurl AppendFormat:@ "mailto:%@", torecipients[0]];

Add cc Person:

Nsarray *ccrecipients = @[@ "[email protected]"];[ Mailurl AppendFormat:@ "cc=%@", ccrecipients[0]];
View Code

Add encryption to send people:

Nsarray *bccrecipients = @[@ "[email protected]"];[ Mailurl AppendFormat:@ "&bcc=%@", bccrecipients[0]];
View Code

Add message subject and message content:

[Mailurl appendString:@ "&subject=my email"]; [Mailurl appendString:@ "&body=<b>Hello</b> world! "];

Open the address, this will jump to the mail sending interface:

NSString *emailpath = [Mailurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];[ [UIApplication sharedapplication] Openurl:[nsurl Urlwithstring:emailpath]];

Ii. using Mfmailcomposeviewcontroller to send mail

Note Before use:

1) The project needs to be imported into the framework: Messageui.framework

2) using the CONTROLELR in the import header file: #import <MessageUI/MessageUI.h>

Gets whether the user has set up a mail account:

if // user has set up mail account    // call the code that sent the message }

Sendemailaction Method Code:

- (void) sendemailaction{//Mail ServerMfmailcomposeviewcontroller *mailcompose =[[Mfmailcomposeviewcontroller alloc] init]; //set up a mail agent[Mailcompose setmailcomposedelegate:self]; //Set Message subject[Mailcompose Setsubject:@"I am the subject of the mail"]; //Set Recipient[Mailcompose settorecipients:@[@"[email protected]"]]; //Set cc people[Mailcompose setccrecipients:@[@"[email protected]"]]; //set up a CC[Mailcompose setbccrecipients:@[@"[email protected]"]]; /** * Set the body content of the message*/NSString*emailcontent =@"I am the email content"; //is HTML format[Mailcompose setmessagebody:emailcontent Ishtml:no]; //If you are using HTML format, the following code//[Mailcompose setmessagebody:@]         /** * Add attachments*/UIImage*image = [UIImage imagenamed:@"Image"]; NSData*imagedata =uiimagepngrepresentation (image); [Mailcompose addattachmentdata:imagedata MimeType:@""FileName:@"Custom.png"]; NSString*file = [[NSBundle mainbundle] Pathforresource:@"Test"OfType:@"PDF"]; NSData*pdf =[NSData Datawithcontentsoffile:file]; [Mailcompose addattachmentdata:pdf MimeType:@""FileName:@"7 days proficient in IOS233333"]; //pop-up mail send view[self presentviewcontroller:mailcompose animated:yes completion:nil];}

Proxy methods for Mfmailcomposeviewcontrollerdelegate:

- (void) Mailcomposecontroller: (Mfmailcomposeviewcontroller *Controller Didfinishwithresult: (mfmailcomposeresult) Result error: (Nserror*) error{Switch(Result) { CaseMfmailcomposeresultcancelled://User cancels editNSLog (@"Mail Send canceled ...");  Break;  CaseMfmailcomposeresultsaved://Users Save MessagesNSLog (@"Mail saved ...");  Break;  CaseMfmailcomposeresultsent://user clicks SendNSLog (@"Mail sent ...");  Break;  CaseMfmailcomposeresultfailed://user attempts to save or send a message failedNSLog (@"Mail Send errored:%@ ...", [Error localizeddescription]);  Break; }        //Close mail Send view[self Dismissviewcontrolleranimated:yes completion:nil];}

Program run:

In the mail sent by iOS, the attachment will be displayed directly below the text, but do not mistakenly think that the picture is placed in the text, the two are different!

Iii. use of third-party library skpsmtpmessage to send mail

Note Before use:

1) Download third-party libraries (at the beginning of the article)

2) Import class #import "SKPSMTPMessage.h", #import "Nsdata+base64additions.h"

Set Basic parameters:

Skpsmtpmessage *mail =[[Skpsmtpmessage alloc] init]; [Mail setsubject:@"I'm the subject ."];//Set Message subject[Mail settoemail:@"fill your own @qq.com."];//Target Mailbox[Mail setfromemail:@"fill your own @qq.com."];//Sender's Mailbox[Mail setrelayhost:@"smtp.qq.com"];//Send mail proxy server[Mail Setrequiresauth:yes]; [Mail setlogin:@"fill your own @qq.com."];//Sender Email Account[Mail SetPass:@"fill in your own"];//Sender Email Password[Mail Setwantssecure:yes];//requires encryption[Mail setdelegate:self];

To set the message body content:

NSString *content = [NSString stringwithcstring:" test content "@ "text/ Plain"@"8bit"};

Add attachments (The following code can be found in the Dmeo of the Skpsmtpmessage Library):

NSString *vcfpath = [[NSBundle mainbundle] Pathforresource:@"Test"OfType:@"VCF"]; NSData*vcfdata =[NSData Datawithcontentsoffile:vcfpath]; Nsdictionary*vcfpart = [Nsdictionary Dictionarywithobjectsandkeys:@"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"test.vcf\"", Kskpsmtppartcontenttypekey,@"attachment;\r\n\tfilename=\"test.vcf\"", Kskpsmtppartcontentdispositionkey,[vcfdata Encodebase64fordata],kskpsmtppartmessagekey,@"Base64", Kskpsmtppartcontenttransferencodingkey,nil];

To execute the sending message code:

// Message header field, message content format, and transfer encoding [Mail send];

The Skpsmtpmessage agent can be informed of success/failure for subsequent steps processing:

-(void) Messagesent: (Skpsmtpmessage *) message{    NSLog (@ "%@", message);} -(void) messagefailed: (skpsmtpmessage *) message Error: (Nserror *) error{    NSLog (@ " Message-%@\nerror-%@ " , message, error);}

What the? No, only because of caprice.

What is taken here is not to notify the user to send the message, so no.

Summary: Originally the third party library that I do not want to write out, because always feel insecure, do not ask me why, man's intuition? In fact, the code is too ugly to understand, it may be I am too technical food.

This article draws on:

Http://blog.sina.com.cn/s/blog_7d280d7c0101da7d.html

Http://www.cnblogs.com/zhuqil/archive/2011/07/21/2112816.html

http://blog.csdn.net/zhibudefeng/article/details/7677421

Blog Garveycalvin

Blog Source: http://www.cnblogs.com/GarveyCalvin/

This article copyright belongs to the author and the blog Garden altogether, welcome reprint, but must retain this paragraph statement, and gives the original link, thanks cooperation!

iOS Development-Send email (e-mail) method to organize the collection (total 3 kinds)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.