Unable to send email through my app - objective-c

I am new to iphone development. I am building an app through which i can send the email.I am using the following code
- (IBAction)btnsendPressAction:(id)sender {
if([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mailer=[[MFMailComposeViewController alloc]init];
mailer.mailComposeDelegate=self;
[mailer setSubject:#"A Message for testing"];
NSArray *toRecipients = [NSArray arrayWithObjects:#"rajshetty2125#gmail.com", #"secondMail#example.com", nil];
[mailer setToRecipients:toRecipients];
UIImage *image=[UIImage imageNamed:#"logo.png"];
NSData *imageData=UIImagePNGRepresentation(image);
[mailer addAttachmentData:imageData mimeType:#"image/png" fileName:#"logo.png"];
NSString *emailBody=#"This is test email";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
mailer.modalPresentationStyle = UIModalPresentationPageSheet ;
}
else{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"failure" message:#"Alert" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
My problem is mailComposeController delegate is not getting called and I am not able to send email through my app.I went through many links , but every where I found the same method. Can anyone help me on this ?

You won't be able to send email from Simulator. You can only check this functionality on iOS device with any account configured in Mail application.

Here use this link and your add(configured) an account in device then only you can send the mail.

This snippet is working for me:
if ([MFMailComposeViewController canSendMail]) {
self.mailController = [[MFMailComposeViewController alloc] init];
[self.mailController setSubject:#"Invitation"];
[self.mailController setMessageBody:#"Message" isHTML:NO];
self.mailController.mailComposeDelegate = self;
[self presentModalViewController:self.mailController animated:YES];
}
but make sure that you're implement delegate in interface
#interface MyClass() <MFMailComposeViewControllerDelegate>
and check your callback method:
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
}

hey i am not sure but may be it's helpful, replace your last line
mailer.modalPresentationStyle = UIModalPresentationPageSheet ;
with
[self presentModalViewController: mailer animated:YES];

Related

Adding NSData attachment to Twitter as an image post

Currently my app gives the option to save to device, or email, the latter attaching the image automatically to the mail, I am looking to add a post to twitter option, simply attaching the image and posting to Twitter, I have done this a few times with other apps, but cannot seem to get this one working.
Here is the process for email;
-(void)displayComposerSheet
{
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
[mail setSubject:#""];
NSString* path =[NSHomeDirectory() stringByAppendingPathComponent:#"Documents/email.png"];
[mSplashView SaveResultImage:path];
[mail addAttachmentData:[NSData dataWithContentsOfFile:path] mimeType:#"image/png" fileName:#"Attached image"];
NSString *msg = [NSString stringWithFormat:#"I made this image!", [UIDevice currentDevice].model];
NSString* mailcontent = [NSString stringWithFormat:#"<br> %# <br>", msg];
[mail setMessageBody:mailcontent isHTML:YES];
[self presentModalViewController:mail animated:YES];
[mail release];
}
I am struggling to see how I can use similar to attach the image to Twitter, I currently use this code, but it crashes when attempting to post;
TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
[self presentViewController:twitter animated:YES completion:nil];
NSString* path =[NSHomeDirectory() stringByAppendingPathComponent:#"Documents/email.png"];
[mSplashView SaveResultImage:path];
[twitter setInitialText:#"I made this image!"];
[twitter addURL:[NSData dataWithContentsOfFile:path]];
twitter.completionHandler = ^(TWTweetComposeViewControllerResult res) {
if(res == TWTweetComposeViewControllerResultDone) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Thank you" message:#"Posted successfully to Twitter." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
if(res == TWTweetComposeViewControllerResultCancelled) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Cancelled" message:#"You Cancelled posting the Tweet." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
[self dismissViewControllerAnimated:YES completion:nil];
};
}
Normally I could simply call [twitter addImage:]; but unfortunately it seems the image is not grabbed correctly without going through the processes above in the mail sheet.
You can't pass NSData for -addURL: method.
If your image store on disk, you can create image with [UIImage imageWithContentsOfFile:imagePath] method. Next add it with -addImage:
NSString* path =[NSHomeDirectory() stringByAppendingPathComponent:#"Documents/imgtweet.png"];
[UIImagePNGRepresentation(imageView.image) writeToFile:path atomically:YES];
//NSLog(#"path %#",path);
UIImage *new_image = [UIImage imageWithContentsOfFile:path];
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:self.txtContent.text];
[tweetSheet addImage:new_image];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
Using Previous Answer,Thanks :)
Happy coding :)

MFMailComposer Dismissing immediately after launch

I am trying to launch the MFMailComposer on the iOS 7 simulator and as soon as it comes up it immediately dissmises itself and I get the following error in the debugger.
_serviceViewControllerReady:error: Error Domain=NSCocoaErrorDomain Code=4097 "The operation couldn’t be completed. (Cocoa error 4097.)"
Here is my code
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 0:
break;
case 1:{
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
mailViewController.mailComposeDelegate = self;
[mailViewController setSubject:[NSString stringWithFormat:#"%# Totals Report",_teamStats.relationshipTeam.teamName]];
[mailViewController setMessageBody:#"\n\n\n\n\nSent From HoopMetrics" isHTML:NO];
// Attach a doc to the email
NSData* data = [_teamStats.relationshipTeam pdfDataFromString:_teamStats.teamTotalsAsString];
[mailViewController addAttachmentData:data mimeType:#"application/pdf" fileName:#"Totals Report"];
[self presentViewController:mailViewController animated:YES completion:nil];
}
else{
HMAlertView*alert = [[HMAlertView alloc]initWithTitle:#"No Email" message:#"Please, set up an email account on your device" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
break;
}
I faced the same problem. Just turn off appearance customization for UINavigationBar or UIBarButtonItem or some another element that MFMailComposeViewController may use.
You can get around this with the following hack using performSelector:
- (IBAction)sendEmail:(id)sender {
[self performSelector:#selector(showEmailComposer) withObject:nil afterDelay:0.0];
}
-(void) showEmailComposer{
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
//Set recipients...other stuff
[mailViewController setToRecipients:recipients];
[mailViewController setSubject:subject];
[mailViewController setMessageBody:body isHTML:isHTML];
mailViewController.title = #"Email VC Title";
mailViewController.mailComposeDelegate = delegate;
[self presentViewController:mailViewController
animated:YES
completion:NULL];
}

iOS Mail Composer Won't Dismiss

I am trying to take a screenshot and email it using the mail composer. Everything works great except the mail composer won't dismiss. This post seems to have the same problem, but the solution provided did not work for me. Can't dismiss the email composer view in iPhone?
- (IBAction)Email:(id)sender {
UIGraphicsBeginImageContext(self.view.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * imageData = UIImageJPEGRepresentation(image, 1.0);
if ( [MFMailComposeViewController canSendMail] ) {
MFMailComposeViewController * mailComposer = [[[MFMailComposeViewController alloc] init] autorelease];
mailComposer.delegate = self;
[mailComposer setSubject:#"Risk Assessment"];
[mailComposer addAttachmentData:imageData mimeType:#"image/jpeg" fileName:#"attachment.jpg"];
[self presentModalViewController:mailComposer animated:YES];
}
}
The above code works great. How do I call this bottom portion. It seems like the compiler just skips past it.
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
if (error){
NSString *errorTitle = #"Mail Error";
NSString *errorDescription = [error localizedDescription];
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:errorTitle message:errorDescription delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[errorView show];
[errorView release];
}
[controller dismissModalViewControllerAnimated:YES];
}
Thanks in advance.
Try
mailComposer.mailComposeDelegate = self;
instead of
mailComposer.delegate = self;
From the MFMailComposeViewController documentation:
#property(nonatomic,assign) id<MFMailComposeViewControllerDelegate> mailComposeDelegate;
The delegate object is responsible for dismissing the view presented by this view controller at the appropriate time. Therefore, you should always provide a delegate and that object should implement the methods of the MFMailComposeViewControllerDelegate protocol.
I am pretty sure that last line should be
[self dismissModalViewControllerAnimated:YES];
The ViewController that presented the view modally, also dismisses it.

how to test MFMailComposeViewController in simulator

Is there a way to test sending emails from MFMailComposeViewController in iphone simulator ?
No you can't test it on simulator...(I mean your mail won't be delivered).we will be able to test limited things like: how the view will be,what happens when the user clicks on cancel button etc...
To test whether, the mail was delivered or not, you have to use a Device. The device should be configured with some mail(ex:gmail) in your settings.
Actual mail sending is not possible from the simulator.
Install the APP on a phone to test that.
However you can test everything that your APP can do/control/specify in the simulator.
Everything after the pressing of the Send button is Apple, so you can assume that is
working okay.
Read Sending mail with MFMailComposeViewController
First include MessageUI framework an implement MFMailComposeViewControllerDelegate.
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
#interface MainViewController : UIViewController <MFMailComposeViewControllerDelegate> {
}
then implement a method like this one an the delegate method for removing the mail controller.
- (IBAction)pressentMailController:(id)sender {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Test subject!"];
// Set up the recipients.
/*NSArray *toRecipients = [NSArray arrayWithObjects:#"first#example.com",
nil];
NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com",
#"third#example.com", nil];
NSArray *bccRecipients = [NSArray arrayWithObjects:#"four#example.com",
nil];
[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];
*/
// Attach an image to the email.
/*NSString *path = [[NSBundle mainBundle] pathForResource:#"ipodnano"
ofType:#"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"image/png"
fileName:#"ipodnano"];
*/
// Fill out the email body text.
NSString *emailBody = #"It is raining in sunny California!";
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
[self presentModalViewController:picker animated:YES];
[picker release]; // Can safely release the controller now.
}
// The mail compose view controller delegate method
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
[self dismissModalViewControllerAnimated:YES];
}
The code allows to add recipients, body, subject and attachements. Uncomment the lines as needed.

Trying to Integrate Mail Into my app, getting 2 warnings

I'm trying to integrate sending mail into my app, but I end up with 2 warnings. I am using Obj-C, the Cocos2d Framework. This is my code.
-(void) mailTapped: (id) sender {
MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
composer.mailComposeDelegate = self;
if ([MFMailComposeViewController canSendMail]) {
[composer setToRecipients:[NSArray arrayWithObjects:#"", nil]];
[composer setSubject:#"Check Out This Awesome App!"];
[composer setMessageBody:#"I found this great game on the App Store! It's called Mole Attack. It's a side scroller with an epic story. You can check out some screenshots of the gameplay and download it here. Download link - " isHTML:NO]; //Include link and pics
[self presentModalViewController:composer animated:YES]; // <--- warning - GameOver (name of class) may not respond to '-presentModalViewController:animated:'
}
}
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissModalViewControllerAnimated:YES]; // <--- warning - GameOver may not respond to '-dismissModalViewControllerAnimated:YES'
if (result == MFMailComposeResultFailed) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failed" message:#"The email was not sent. You must be in wifi or 3G range. Try again later." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Thanks in advance!
Are you sure your GameOver class is inheriting from UIViewController? That's the class that defines the two methods that you're getting warnings about.