Implementing the MFMailComposeViewControllerDelegate and add it to your viewcontroller - iphone

I'm trying to setup the ability to email from within my application. My app is based on the SpeakHere example project which uses an object to run all it's UI:
This has made it very confusing for me as to how I need to set up MFMailComposeViewControllerDelegate, etc.
This is somewhat an extension of my previous question.
Any help?

I solved this problem using this example code.

Complete sample code:
- (IBAction)email:(id)sender {
if ([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
[mail setSubject:#"Sample Subject"];
[mail setMessageBody:#"Here is some main text in the email!" isHTML:NO];
[mail setToRecipients:#[#"testingEmail#example.com"]];
[self presentViewController:mail animated:YES completion:NULL];
}else {
NSLog(#"This device cannot send email");
}
}
#pragma mark - MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
switch (result) {
case MFMailComposeResultSent:
NSLog(#"You sent the email.");
break;
case MFMailComposeResultSaved:
NSLog(#"You saved a draft of this email");
break;
case MFMailComposeResultCancelled:
NSLog(#"You cancelled sending this email.");
break;
case MFMailComposeResultFailed:
NSLog(#"Mail failed: An error occurred when trying to compose this email");
break;
default:
NSLog(#"An error occurred when trying to compose this email");
break;
}
[self dismissViewControllerAnimated:YES completion:NULL];
}

Related

iPhone to use MFMailComposer to send email from app?

In my application i am able to send email using MFMailComposer.
suppose if i have gmail account in my iPhone and i am using my app to send the email , i am able to send email to others
but suppose if i have yahoo account in my iPhone and i am using my app to send email,i am not able to send email.
I really don't no what is the problem,does MFMailComposer using gmail account only or something wrong with m code.
please help me out for this.
following is my code:
-(void)SENDEMAIL
{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
NSArray* arr = [[dictUser valueForKey:#"recipients"] componentsSeparatedByString:#","];
NSLog(#"mailcomporeci%#",dictUser);
NSLog(#"arr:%#",arr);
[mailComposer setToRecipients:arr];
//[mailComposer setSubject:[NSString stringWithFormat:#"Scheduled Email %#",arr]];
[mailComposer setSubject:#"Scheduled Email"];
[mailComposer setMessageBody:[dictUser objectForKey:#"message"] isHTML:NO];
mailComposer.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self.tabBarController presentModalViewController:mailComposer animated:YES];
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(hackMail:) userInfo:mailComposer repeats:NO];
}
}
-(void)hackMail:(NSTimer*)theTimer {
MFMailComposeViewController *mailController = theTimer.userInfo;
UIBarButtonItem *sendBtn = mailController.navigationBar.topItem.rightBarButtonItem;
id targ = sendBtn.target;
[targ performSelector:sendBtn.action withObject:sendBtn];
}
#pragma mark Mail Compose Delegate Methods
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
switch (result)
{
case MFMailComposeResultCancelled:
{
break;
}
case MFMailComposeResultSaved:
{
break;
}
case MFMailComposeResultSent:
{
break;
}
case MFMailComposeResultFailed: {
break;
}
default:
break;
}
[self.tabBarController dismissModalViewControllerAnimated:YES];
}
Try it and check out the result :
if([MFMailComposeViewController canSendMail]){
[self presentModalViewController:mailController animated:YES];
}
May be your device is not configured to any account to send mail.

How to share or post by mail, twitter and facebook from the current application?

I am implementing an application from which I have to share that applications on Facebook, Twitter as well as by mail. As my application is not a game, I just want to put an application icon, application name, iTunes link of that application and a small description of the application. I have implemented code which allow me to send a mail with attachment. Is that useful here? How can I do this?
1. For Facebook.
FBGraph is a much better way to use the Facebook API in your application.
Download the FBGraph API documents folder and then add it to in your folder. Read the instructions on the Facebook developer site.
This is the sample code and let me know if you have any query about it.
2. For EMail
Add MessageUI.framework in your project. Import the header file in your ViewController.h file:
#import <MessageUI/MFMailComposeViewController.h>
Set the delegate:
UIViewController<MFMailComposeViewControllerDelegate>
And after that, open your mail composer like this:
-(void)yourEmailbuttonClick:(id)sender
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Hello!! your subject here"];
// Set up recipients
UIImage *image = [UIImage imageNamed:#"anyImage.png"];
NSData *myData = UIImageJPEGRepresentation(image, 1.0);
[picker addAttachmentData:myData mimeType:#"image/jpg" fileName:#"image"];
[self presentModalViewController:picker animated:YES];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:
// message.text = #"Result: canceled";
break;
case MFMailComposeResultSaved:
// message.text = #"Result: saved";
break;
case MFMailComposeResultSent:
// message.text = #"Result: sent";
break;
case MFMailComposeResultFailed:
// message.text = #"Result: failed";
break;
default:
// message.text = #"Result: not sent";
break;
}
[self dismissModalViewControllerAnimated:YES];
}
3. For Twitter
Add Twitter.framework in your project. Import the header file in your ViewController.h file and import:
#import <Twitter/Twitter.h>
Now call the Twitter composer view like this:
-(void)yourTwitterbuttonClick:(id)sender
{
if([TWTweetComposeViewController canSendTweet])
{
UIImage *image = [UIImage imageNamed:#"anyImage.png"];
TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
// Set initial text
[tweetViewController setInitialText:#"your text here"];
if (image)
{
[tweetViewController addImage: image];
}
tweetViewController.completionHandler = ^(TWTweetComposeViewControllerResult result)
{
if(result == TWTweetComposeViewControllerResultDone)
{
// The user finished composing a tweet
alert.title=#"Status";
alert.message=#"Tweet sent";
[alert show];
}
else
if(result == TWTweetComposeViewControllerResultCancelled)
{
// The user cancelled composing a tweet
alert.title = #"Status";
alert.message = #"Tweet cancelled";
[alert show];
}
[self dismissViewControllerAnimated:YES completion:nil];
};
[self presentViewController:tweetViewController animated:YES completion:nil];
}
}
Have a look at ShareKit.
This is a list of supported services:
Supported Services:
Delicious
Email
Facebook
Google Reader
Instapaper
Pinboard
Read It Later
Tumblr
Twitter
You can also do this one by one.
Facebook http://developers.facebook.com/docs/reference/iossdk/
Twitter https://developer.apple.com/library/ios/#documentation/Twitter/Reference/TWTweetSheetViewControllerClassRef/Reference/Reference.html
Mail http://developer.apple.com/library/ios/#documentation/MessageUI/Reference/MFMailComposeViewController_class/Reference/Reference.html

How to send email using UIBarButtonItem [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
how to send email using UIbarbuttonitem without using MFMailComposerViewController
As shown in the image this app used to send mail on send button's click.
I found that it is not showing MFMailComposerViewController.
How can it be possible? How do I get this functionality?
Sounds like you just need to read a tutorial carefully.
I found this via Google:
New In iPhone 3.0 Tutorial Series, Part 2: In App Email, MessageUI
Yes, it says "iPhone 3.0" but the same concepts and code should work perfectly fine in iOS 5.
- (void)MailButton:(id)sender
{
if ([MFMailComposeViewController canSendMail]) {
//atableView.scrollEnabled=YES;
//[socailNetworkView removeFromSuperview];
// self.navigationItem.title = #"Contents";
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
mailViewController.mailComposeDelegate = self;
[mailViewController setSubject:#""];
[mailViewController setMessageBody:#"" isHTML:NO];
NSString *string = [NSString stringWithFormat:#"", nil];
NSArray *mailArr = [[NSArray alloc] initWithObjects:string,nil];
[mailViewController setToRecipients:mailArr];
[self presentModalViewController:mailViewController animated:YES];
[mailViewController release];
}
else {
NSLog(#"Device is unable to send email in its current state");
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
NSLog(#"Mail");
NSString *str=#"";
switch (result) {
case MFMailComposeResultCancelled:
NSLog(#"Mail send canceled.");
str=#"\nMail sending cancelled";
//msgLabel.text=str;
// [msgLabel setFont:[UIFont fontWithName:#"Arial" size:18]];
// msgLabel.textColor=[UIColor colorWithRed:(54.0/255.0) green:(2.0/255) blue:(1.0/255) alpha:1.0];
/*
Execute your code for canceled event here ...
*/
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved.");
str=#"Mail saved";
/*
Execute your code for email saved event here ...
*/
break;
case MFMailComposeResultSent:
NSLog(#"Mail sent.");
str=#"Mail sent";
/*
Execute your code for email sent event here ...
*/
break;
case MFMailComposeResultFailed:
str=#"Mail not sent";
NSLog(#"Mail send error: %#.", [error localizedDescription]);
/*
Execute your code for email send failed event here ...
*/
break;
default:
break;
}
//alertLabel.text=str;
// [viewAlert setBackgroundColor:[UIColor clearColor]];
// [self.view addSubview:viewAlert];
[self dismissModalViewControllerAnimated:YES];
}

Not able to send email from an app with MFMailComposeViewController

I'm having some hard time trying to send an email from my app.
I tried this code from iCodeBlog (http://icodeblog.com/2009/11/18/iphone-coding-tutorial-in-application-emailing/)
-(void)sendEmail:(id)sender
{
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
if ([MFMailComposeViewController canSendMail]) {
//Setting up the Subject, recipients, and message body.
[mail setToRecipients:[NSArray arrayWithObjects:#"myEmail#email.com",nil]];
[mail setSubject:#"Subject of Email"];
[mail setMessageBody:#"Message of email" isHTML:NO];
//Present the mail view controller
[self presentModalViewController:mail animated:YES];
}
//release the mail
[mail release];
}
//This is one of the delegate methods that handles success or failure
//and dismisses the mail
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[self dismissModalViewControllerAnimated:YES];
if (result == MFMailComposeResultFailed) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message Failed!" message:#"Your email has failed to send" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
It says it send the email and no error occurs but I never get the email in my inbox.
I tried sending them to different email accounts and tried sending them from different accounts as well, no error occurs but I never get the email.
Any ideas?
If it's important, I get this message on the Debugger Console when I start typing the To: email
DA|Could not open the lock file at /tmp/DAAccountsLoading.lock. We'll load the accounts anyway, but bad things may happen
===== EDIT ======
I just realized that all those emails were sent to my Outbox on Mail.app. Aren't they sent automatically when I click send? If not, then what can I do to make them be sent when the user presses the Send button on MFMailComposeView? Or perhaps call the Mail.app and make those emails be sent.
Use this code this will definitely work:
-(IBAction)send{
[self callMailComposer];
}
-(void)callMailComposer{
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
[self launchMailAppOnDevice];
}
else
{
[self launchMailAppOnDevice];
}
}
#pragma mark -
#pragma mark Compose Mail
#pragma mark
// Displays an email composition interface inside the application. Populates all the Mail fields.
-(void)displayComposerSheet{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
NSString *tosubject =#"";
[picker setSubject:tosubject];
// Set up recipients
[picker setCcRecipients:nil];
[picker setBccRecipients:nil];
[picker setToRecipients:nil];
[picker setMessageBody:strNewsLink isHTML:NO];
[self presentModalViewController:picker animated:YES];
if(picker) [picker release];
if(picker) picker=nil;
}
// 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* alertMessage;
// message.hidden = NO;
// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:
alertMessage = #"Email composition cancelled";
break;
case MFMailComposeResultSaved:
alertMessage = #"Your e-mail has been saved successfully";
break;
case MFMailComposeResultSent:
alertMessage = #"Your email has been sent successfully";
break;
case MFMailComposeResultFailed:
alertMessage = #"Failed to send email";
break;
default:
alertMessage = #"Email Not Sent";
break;
}
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:#"My app name"
message:alertMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[self dismissModalViewControllerAnimated:YES];
}
#pragma mark
#pragma mark Workaround
#pragma mark
// Launches the Mail application on the device.
-(void)launchMailAppOnDevice{
NSString *recipients = #"mailto:?cc=&subject=";
NSString *body = #"&body=";
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
digging up an old thread here... maybe I can save future frustrations when dealing with MFMAilComposerViewController that does not send emails.
my app would send emails on 4 of my 5 test devices and I could not understand what the difference was on the 5th. The problem was an incorrectly setup Gmail account. The MFMailComposerViewController error trap method never returned any errors, it just did not send the email. The problem was an incorrect email address or email password. I discovered this by asking the device user for his email logon info and then an error alert appeared when I tried to logon to his Gmail account. The assumption, yes, my bad, was that canSendMail would check for a valid email account...
Btw i hope you are testing this functionality in device as if you try to run this code in Simulator,it will show e-mail sent successfully,but the e-mail is never sent.
Thanks
Swift 4 version
let myController:MFMailComposeViewController = MFMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
myController.mailComposeDelegate = self
myController.setToRecipients(["example#example.com"])
self.present(myController, animated: true, completion: nil)
}

How to Create SMS application in iPhone

I am new to iphone development, i want to create SMS application in my application.I have created mail application using "messageUI.framework".Is there any framework for creating SMS application.I have no idea of it, so tell me the way of approaching this task. Please guide me to achieve my task.Please help me out.Thanks.
Unfortunately, there is no built-in view controller for sending SMS like MFMailComposeViewController for email.
As of iOS 4.0, you can use the MFMessageComposeViewController, a counterpart to the email-only MFMailComposeViewController. This lets you lay out and send an SMS message.
Additionally, you can use the SMS URL scheme, like is decribed in this question. However, it appears that you cannot prepopulate the body of an SMS message this way.
You can use the MFMessageComposeViewController class, as documented by Apple.
For that, first add MessageUI.framework to your project.
// in .h file make the following change
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMessageComposeViewController.h>
#interface YourViewController: UIViewController <MFMessageComposeViewControllerDelegate>
// then in .m file do the following.
- (void)viewDidLoad {
[super viewDidLoad];
SMSLabel = [[UILabel alloc] initWithFrame:CGRectMake(30.0, 340.0, 260.0, 30.0)];
SMSLabel .frame = CGRectMake(30.0, 340.0, 260.0, 30.0);
SMSLabel .adjustsFontSizeToFitWidth = YES;
SMSLabel .hidden = YES;
SMSLabel .text = #"";
SMSLabel .userInteractionEnabled = NO;
SMSLabel.alpha=0.0;
[self.view addSubview:SMSLabel ];
}
-(void)ComposerSheet
{
MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.messageComposeDelegate = self;
picker.recipients = [NSArray arrayWithObject:#"1234567"];
picker.body = #"iPhone OS4";
[self presentModalViewController:picker animated:YES];
[picker release];
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
SMSLabel.alpha=1.0;
switch (result)
{
case MessageComposeResultCancelled:
SMSLabel .text = #"Result: canceled";
NSLog(#"Result: canceled");
break;
case MessageComposeResultSent:
SMSLabel .text = #"Result: sent";
NSLog(#"Result: sent");
break;
case MessageComposeResultFailed:
SMSLabel .text = #"Result: failed";
NSLog(#"Result: failed");
break;
default:
SMSLabel .text = #"Result: not sent";
NSLog(#"Result: not sent");
break;
}
[self dismissModalViewControllerAnimated:YES];
}
Sending messages is somewhat easy — you can usually send an email to a specially formatted number like 555.555.5555#verizon.net (example only, not sure of real format) and it will send to the device. There is not going to be an easy way to receive sms messages in your app natively.
You can, however, try using one of many free sms apis such as ZeepMobile
MFMessageComposeViewController will send the message through iMessage app. But If you want to send sms through network career of your iPhone then following code will help you
NSString *phoneToCall = #"sms:";
NSString *phoneToCallEncoded = [phoneToCall stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [[NSURL alloc] initWithString:phoneToCallEncoded];
[[UIApplication sharedApplication] openURL:url];