iOS send mail (e-mail) method to organize the collection

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 email 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!"];
Note: If you do not add cc or BCC, the theme needs to be set to subject=my email, otherwise the message will have no subject.

mailto usage, example: <a href= "Mailto:[email protected]?subject=test&[email protected]&body=use mailto Sample" > Send mail</a>

For details, you can check the syntax yourself.


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

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





650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/57/9B/wKioL1SgszDBnA34AAEMLzw-tN8285.jpg "border=" 0 " Width= "422" style= "line-height:normal;"/>





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 ([Mfmailcomposeviewcontroller Cansendmail]) {//user has set up mail account
[Self sendemailaction]; Calling code to send a message
}


Sendemailaction Method Code:

-(void) sendemailaction
{
Mail server
Mfmailcomposeviewcontroller *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 Mail 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)
{
Case mfmailcomposeresultcancelled://user canceled Edit
NSLog (@ "Mail send canceled ...");
Break
Case mfmailcomposeresultsaved://user Save message
NSLog (@ "Mail saved ...");
Break
Case mfmailcomposeresultsent://user clicks Send
NSLog (@ "Mail sent ...");
Break
Case mfmailcomposeresultfailed://user failed to save or send message
NSLog (@ "Mail send errored:%@ ...", [Error localizeddescription]);
Break
}
Close Mail Send view
[Self dismissviewcontrolleranimated:yes completion:nil];
}


Program run:


650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/57/9E/wKiom1Sgsn7w9peAAAJ4qco4Nuw664.jpg "border=" 0 " "Width=" style= "line-height:normal;"/>



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 am the subject"]; Set Message subject
[Mail settoemail:@ "Fill in your own @qq.com"]; Target Mailbox
[Mail setfromemail:@ "Fill in your own @qq.com"]; Sender's mailbox
[Mail setrelayhost:@ "smtp.qq.com"]; Send mail proxy server
[Mail Setrequiresauth:yes];
[Mail setlogin:@ "Fill in 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" encoding:nsutf8stringencoding];
Nsdictionary *plainpart = @{kskpsmtppartcontenttypekey: @ "Text/plain", Kskpsmtppartmessagekey:content, Kskpsmtppartcontenttransferencodingkey: @ "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:

[Mail Setparts:@[plainpart, Vcfpart]]; 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, decisive further studyiOS app encryptionGo ~

iOS send mail (e-mail) method to organize the collection

Related Article

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.