How to send an email to a receipent in background in iOS5? - iphone

In an iPhone app,I want to send an email to a person who has forgotten about their passcode . I want to send the mail in background (cant use MFMailComposeViewController for this) and also the app must not be pushed to background . Is there a way to achieve this?

The best way of doing this is using SKPSMTPMessage. You can download it from here: https://github.com/jetseven/skpsmtpmessage This is a very easy solution that I have used before for using "Forgot Password" solutions in iOS apps. To implement simply drag the downloaded files into your application, #import the the "SKPSMTPMessage.h" into your class, and implement the following code:
.h
#import "SKPSMTPMessage.h"
#interface SomeView : UIViewController <SKPSMTPMessageDelegate> {
}
- (IBAction)forgotPassword;
.m
- (IBAction)forgotPassword {
SKPSMTPMessage *forgotPassword = [[SKPSMTPMessage alloc] init];
[forgotPassword setFromEmail:#"some-email#gmail.com"]; // Change to your email address
[forgotPassword setToEmail:#"user-email#gmail.com"]; // Load this, or have user enter this
[forgotPassword setRelayHost:#"smtp.gmail.com"];
[theMessage setRequiresAuth:YES]; // GMail requires this
[forgotPassword setLogin:#"some-email#gmail.com"]; // Same as the "setFromEmail:" email
[forgotPassword setPass:#"password"]; // Password for the Gmail account that you are sending from
[forgotPassword setSubject:#"Forgot Password: My App"]; // Change this to change the subject of the email
[forgotPassword setWantsSecure:YES]; // Gmail Requires this
[forgotPassword setDelegate:self]; // Required
NSString *newpassword = #"helloworld";
NSString *message = [NSString stringWithFormat:#"Your password has been successfully reset. Your new password: %#", newpassword];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain", kSKPSMTPPartContentTypeKey, message, kSKPSMTPPartMessageKey, #"8bit" , kSKPSMTPPartContentTransferEncodingKey, nil];
[forgotPassword setParts:[NSArray arrayWithObjects:plainPart, nil]];
[forgotPassword send];
}
Also be sure to include the following methods in the .m. You can change the contents of the UIAlertViews depending on what you want to display to the user.
- (void)messageSent:(SKPSMTPMessage *)message {
NSLog(#"Message Sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Password Reset" message:#"Check your email for your new password." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error {
NSLog(#"Message Failed With Error(s): %#", [error description]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was an error reseting your password. Please try again later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
You also need to do the following before this will work.
Your Target -> Get Info -> Build -> All Configurations -> Other Link Flags: "-ObjC"
If you need help with this, see http://developer.apple.com/qa/qa2006/qa1490.html
EDIT:
* CFNetwork.framework must also be added for this to work! *
Let me know if you have any more questions.
Thanks,
Jacob

You can't use MFMailComposeViewController to do this. No API will allow you to send emails or any kind of message on behalf of the user without he seeing it.
The only I see is to make a call to your server and the server send the email, something like this:
NSURLRequest requestWithURL:[NSURL urlWithString:#"http://server.com/send_passcode?to=email#lala.com"]];

You cannot send SMS/Email without user acceptance. But there are a lot of web-services in internet which can send SMS/Email. I guess some app uses those services or uses own.

You CAN send email in the background (without using the default MFMail Controller). BUT you still need the user to fill out whatever form (or content you want to email) and have them click "Send".
Here is my post on how to do it. It includes code and images.
Locking the Fields in MFMailComposeViewController
P.S. this works and Apple has approved over 10 of my apps that use this code/method.

In reference to the PostageApp comment below if you wanted to send emails without any hassle of setting up an SMTP client you can check out the PostageKit wrapper for using the PostageApp service. Let's you send emails with a couple lines of code reliably.
https://github.com/twg/PostageKit

May be you should implement PHP script that will send out email to user. In ios, you can use POST method in NSURLConnection to call PHP script. You can find many scripts on Google to send out email to user.

Download SKPSMTP Library and import
#import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h"
-(IBAction)btnRecoverClicked:(id)Sender;
Then implement the method for sending mail in background.
-(IBAction) btnRecoverClicked:(id)sender {
NSString *str=#"Your password is:";
NSString *strUserPassword=[NSString stringWithFormat:#"%# %#",str,struserPassword];
NSLog(#"Start Sending");
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail = #"XXXXX"; //sender email address
emailMessage.toEmail = struserEmail; //receiver email address
emailMessage.relayHost = #"smtp.gmail.com";
//emailMessage.ccEmail =#"your cc address";
//emailMessage.bccEmail =#"your bcc address";
emailMessage.requiresAuth = YES;
emailMessage.login = #"xxxxxxxx"; //sender email address
emailMessage.pass = #"XXXXXXX"; //sender email password
emailMessage.subject =#"Password Recovery";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
NSString *messageBody = [NSString stringWithFormat:#"Your password is: %#",struserPassword]
;
//for example : NSString *messageBody = [NSString stringWithFormat:#"Tour Name: %#\nName: %#\nEmail: %#\nContact No: %#\nAddress: %#\nNote: %#",selectedTour,nameField.text,emailField.text,foneField.text,addField.text,txtView.text];
// Now creating plain text email message
NSDictionary *plainMsg = [NSDictionary
dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
messageBody,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,nil];
//in addition : Logic for attaching file with email message.
/*
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"JPG"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *fileMsg = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx-
unix-mode=0644;\r\n\tname=\"filename.JPG\"",kSKPSMTPPartContentTypeKey,#"attachment;\r\n\tfilename=\"filename.JPG\"",kSKPSMTPPartContentDispositionKey,[fileData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,fileMsg,nil]; //including plain msg and attached file msg
*/
[emailMessage send];
// sending email- will take little time to send so its better to use indicator with message showing sending...
}
To handle the success and fail use
-(void)messageSent:(SKPSMTPMessage *)message{
NSLog(#"delegate - message sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message sent to your mail." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
and
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}

https://github.com/troyz/MailUtil
I have used library above to send mail in background, so it works.
pod "MailUtil", :git => 'https://github.com/troyz/MailUtil.git', :tag => '0.1.0'
Swift code is here:
import MailUtil
SendEmailOperation.setupConfig(withServer: "smtp.foo.com", withFrom: "foo#mailserver.com", withLogin: "foo#mailserver.com", withPassword: "*********")
let operation = SendEmailOperation(to: "foo#mailserver.com", subject: "Hello", body: "world", path: "/selected/path/for/your/file.pdf")
operation?.completionBlock = {
debugPrint("Mail sent!")
DispatchQueue.main.async {
//showMailSentPopup()
}
}
do {
try SendEmailOperation.sendEmail(operation)
} catch {
debugPrint("Mail could not sent or sending result could not handle - \(error)")
}

Related

Trying to send email, getting "use of undeclared unidentified MFMailComposeViewController"

I'm trying to send a email message in my app. I'm trying to use the MFMailComposeViewController object, but getting a error message saying its a "undeclared identifier"
code:
-(IBAction) aContact: (id) sender;
{
if([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mailCtrl = [[[MFMailComposeViewController alloc] init] autorelease];
[mailCtrl setSubject:#"Your TellaFortune Card Reading"];
// [mailCtrl setToRecipients:[NSArray arrayWithObject:#"drblyer#cameosurgery.com"]];
mailCtrl.mailComposeDelegate = self;
NSString *send;
send=[ NSString stringWithFormat: #"%# %#",content,#"\n \n By www.TellaFortune.com"];
[mailCtrl setMessageBody: send isHTML: false];
[self presentModalViewController:mailCtrl animated:NO];
// [mailCtrl release];
}
else
{
UIAlertView *alert=[[ UIAlertView alloc]
initWithTitle:#"Cannot send email"
message: #"Please check internet connection and email set up"
delegate: self
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
[alert show];
}
}
Import framework "MessageUI.framework" to your project and in your .h file add
#import <MessageUI/MessageUI.h>
For anyone who is using Swift and seeing this message:
First go to your project settings in Xcode, select Build Phases, then Link Binary with Libraries, and add "MessageUI.framework" to your project.
Then, in the Swift file in which you want to use a MFMailComposeViewController or implement the MFMailComposeViewControllerDelegate, add:
import MessageUI

FBWebDialogs presentRequestsDialogModallyWithSession is not working?

This code is not generating notification on friend's end.But sending successully generating no error.I am building a app for Game url on friend to invite them to play.i have written below code to send url.it's working fine and not generating no error but user is not getting any request for App.
//Fbwebdialog generating no error
[FBWebDialogs presentRequestsDialogModallyWithSession:[FBSession activeSession]
message:[NSString stringWithFormat:#"I just smashed friends! Can you beat it?"]
title:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Case A: Error launching the dialog or sending request.
NSLog(#"Some errorr: %#", [error description]);
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Invitiation Sending Failed" message:#"Unable to send inviation at this Moment, please make sure your are connected with internet" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
} else {
if (![resultURL query]) {
return ;
NSLog(#"User canceled request.");
} else {
NSDictionary *params = [self parseURLParams:[resultURL query]];
NSMutableArray *recipientIDs = [[NSMutableArray alloc] init];
for (NSString *paramKey in params){
if ([paramKey hasPrefix:#"to["]){
[recipientIDs addObject:[params objectForKey:paramKey]];
}
}
if ([params objectForKey:#"request"]){
NSLog(#"Request ID: %#", [params objectForKey:#"request"]);
NSArray *requestIDs=[params objectForKey:#"request"];
}
if ([recipientIDs count] > 0){
//[self showMessage:#"Sent request successfully."];
//NSLog(#"Recipient ID(s): %#", recipientIDs);
// punGameViewController *pun=[[punGameViewController alloc]initWithNibName:#"punGameViewController" bundle:nil];
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Successfully send" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
// [self.navigationController pushViewController:pun animated:YES];
}
}
}
}];
//end of code here
check it find the reason not generating notification.
I found my answer to this question on a previously answered S/O question. Basically, you need to set the App Store Id and Bundle Id in the Facebook App settings in order for invites to get sent. You can find that info: here
Notifications sent by your app is only received on mobile devices if your app is a game. If your app is not a game, notifications are still delivered to the App Center on the desktop.

iPhone to retrieve gmail account details in app from setting

I am making an application where I want to send an email using smtp server.
It's working fine but if user does not provide the correct gmail account details such as (email id and password) email is not send.
What I want to do is I want to access user gmail account details from setting tab of the iPhone into my app?
Is it possible to do retrieve the gmail account detail into the app?
Please help me out with this.
Following is my code:
-(IBAction)sendemail
{
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
//testMsg.fromEmail = #"Lexi mobile";//nimit51parekh#gmail.com
testMsg.fromEmail = soundOn;
NSLog(#"str_Uname=%#",testMsg.fromEmail);
//str_info = [str_info stringByReplacingOccurrencesOfString:#"," withString:#""];
testMsg.toEmail = [string_emailinfo objectAtIndex:0];
NSLog(#"autoemail=%#",testMsg.toEmail);
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = soundOn;
NSLog(#"autoelogin=%#",testMsg.login);
testMsg.pass = vibrateOn;
NSLog(#"autopass=%#",testMsg.pass);
testMsg.subject = #"Photo Sharing";
testMsg.wantsSecure = YES;
NSURL *url = [[NSURL alloc]initWithString:#"http://itunes.apple.com/us/app/umix-radio/id467041430?mt=8"];
NSString *msg2 = [NSString stringWithFormat:#"<html><b>DOWNLOAD NOW</b>&nbsp&nbsp</html>",url];
NSString *sendmsg=[[NSString alloc]initWithFormat:#"%#",msg2];
NSLog(#"automsg=%#",sendmsg);
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
sendmsg,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
// [self DeleteRowAfterSending];
//[self performSelector:#selector(DeleteRowAfterSending) withObject:nil afterDelay:5.0];
}
-(void)messageSent:(SKPSMTPMessage *)message
{
[message release];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success" message:#"Your email is sent successfully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - message sent");
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
[message release];
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Fail" message:#"Message sending failure" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
What i want to do is i want to access user gamil account details from
setting tab of the iPhone into my app? is it possible to do retrive
the gamil account detail into the app?
No, and with good reason: that functionality would allow any developer access to anyone's e-mail account.
That would be a massive security hole.
Much like it is with Location Services, you're just going to have to ask the user to enter their e-mail address and password. And hope they want to trust your app with that kind of personal information. (Assuming Apple approves your app at all.)
Let the user give your app authorization from Google. check the oauth autorization with google api at their developers site?
https://developers.google.com/accounts/docs/OAuth2
As usual the user signs in with his account through google api and returns back to you an access_token to get information back from his account including his email which you need.

How to add attchment and signature in email through programming in iPhone App/

How can I add video/image/audio as an attachment programmatically in the email in iPhone app iPhone and how can I add Signature? I think it can be done by using html tags but how it can be done. Can you please any sample code for this.
Thanks-
To send attachments: You can use MFMailComposeViewController to send attachments from your app.
1. Add MessageUI framework, and do #import <MessageUI/MFMailComposeViewController.h>
2. In your email button action or however you are sending email, add :
if([MFMailComposeViewController canSendMail]) //IMPORTANT: check if mail can be sent to avoid crash
{
MFMailComposeViewController*mailController=[[MFMailComposeViewController alloc] init];
NSURL*yourUrl=[NSURL fileURLWithPath:yourFilePath];
NSData*attachData=[NSData dataWithContentsOfURL:yourUrl];
mailController.mailComposeDelegate=self;
[mailController addAttachmentData:attachData mimeType:#"yourExtension" fileName:#"yourFileName.yourExtension"];
[mailController setSubject:#"Test Subject"];
[mailController setTitle:#"Test Title"];
if(mailController!=nil)
{
[self presentModalViewController:mailController animated:YES];
}
[mailController release];
}
else //give a prompt showing no mail accounts found
{
UIAlertView*emailAlert=[[UIAlertView alloc] initWithTitle:#"No Email Account Found." message:#"Please set an email account." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[emailAlert show];
[emailAlert release];
}
To set signature: I guess it uses the signature relative to the mail account that has been set. Sorry no idea on how to change it programmatically.

How to send mail from iphone app without showing MFMailComposeViewController?

I want to send mail from my custom iPhone app. I have used MFMailComposeViewController to send mail from my iphone in my previous app. Now, i don't want to show the MFMailComposeViewController to the user, if they click Send Mail button the mail automatically send to the recipient mail address. How can i do this? Can you please help me on this? Thanks in advance.
I have used below code to show the MFMailComposeViewController,
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"Details"];
[controller setMessageBody:#"Hi" isHTML:NO];
[controller setToRecipients:[NSArray arrayWithObjects:#"abcd.m#gmail.com", nil]];
[self presentModalViewController:controller animated:YES];
[controller release];
Sending emails programmatically, without user intervention, from an iphone application, cannot be implemented using any of the Apple frameworks. It could be possible in a jailbroken phone but then it would never see the inside of App Store.
If you want control of email sending, then a better way would be to set up a web service (at your server end) you can post to using an HTTP request. If you are posting to only one address this can work very well, although you may want to get the user to input their return mail address.
Otherwise only the standard dialog is available (this relies on using whatever account they've setup on the device).
The iOS SDK has made it really easy to send email using the built-in APIs. With a few line of codes, you can launch the same email interface as the stock Mail app that lets you compose an email. You can pop up mail composer form , write message and can send plain mail or file attached mail using MFMailComposeViewController class. For more info : Sending e-mail from your iOS App
But, in this section what i am going to explain is about sending emails without showing the mail composer sheet ie. sending emails in background. For this feature, we can not use iOS native MFMailComposer class because it does not allow us to send emails in background instead it pop ups the mail composer view from where user have to tap "send" button , so for this section i am going to use SKPSMTPMessage Library to send emails in background, however email account has to be hardcoded on this method.
Limitations :
sender/receiver email address has to be hardcoded or you have to grab it using some pop up form in your app where user inputs sender/receiver email address. In addition, sender account credentials has to be also hardcoded since there is no way we can grab it from device settings.
Method :
Import CFNetwork.framework to your project.
Include #import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h" // for Base64 encoding
Include to your ViewController
Download SKPSMTPMessage library from
https://github.com/jetseven/skpsmtpmessage
Drag and Drop "SMTPLibrary" folder you have downloaded to your project.
Before proceeding, let you know that i am using sender/receiver email address and sender password hardcoded in the code for this example.But, you may grab this credentials from user, allowing them to input in some sort of forms(using UIViews).
-(void) sendEmailInBackground {
NSLog(#"Start Sending");
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail = #"sender#gmail.com"; //sender email address
emailMessage.toEmail = #"receiver#gmail.com"; //receiver email address
emailMessage.relayHost = #"smtp.gmail.com";
//emailMessage.ccEmail =#"your cc address";
//emailMessage.bccEmail =#"your bcc address";
emailMessage.requiresAuth = YES;
emailMessage.login = #"sender#gmail.com"; //sender email address
emailMessage.pass = #"Passwxxxx"; //sender email password
emailMessage.subject =#"#"email subject header message";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
NSString *messageBody = #"your email body message";
//for example : NSString *messageBody = [NSString stringWithFormat:#"Tour Name: %#\nName: %#\nEmail: %#\nContact No: %#\nAddress: %#\nNote: %#",selectedTour,nameField.text,emailField.text,foneField.text,addField.text,txtView.text];
// Now creating plain text email message
NSDictionary *plainMsg = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey, messageBody,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,nil];
//in addition : Logic for attaching file with email message.
/*
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"JPG"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *fileMsg = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx- unix-mode=0644;\r\n\tname=\"filename.JPG\"",kSKPSMTPPartContentTypeKey,#"attachment;\r\n\tfilename=\"filename.JPG\"",kSKPSMTPPartContentDispositionKey,[fileData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,fileMsg,nil]; //including plain msg and attached file msg
*/
[emailMessage send];
// sending email- will take little time to send so its better to use indicator with message showing sending...
}
Now, handling delegate methods :
// On success
-(void)messageSent:(SKPSMTPMessage *)message{
NSLog(#"delegate - message sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message sent." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
// On Failure
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
Ok, thats all from the coding side. hope this tutorial may find useful for you guyz