How to send an E-Mail inside of an app in Xcode? - ios

I am new to xcode, and am wondering how to send email in an app! My code is below, but I keep getting the error "No visible #interface for 'jakem' declares the selector 'presentViewControllerAnimated:'". Is my code completely wrong? Or did I just forget to declare the selector, and how do I declare the selector? I have researched all over the internet for at least an hour, and nothing is working. Someone please help me!
-(IBAction)sendEmail{
MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
[composer setMailComposeDelegate:self];
if ([MFMailComposeViewController canSendMail]) {
[composer setToRecipients:[NSArray arrayWithObjects:#"FrankMurphy.CEO#RomansXIII.com", nil]];
[composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentViewController:composer animated:YES];
}
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
if(error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"error" message:[NSString stringWithFormat:#"error %#", [error description]] delegate:nil cancelButtonTitle:#"dismiss" otherButtonTitles:nil, nil];
[alert show];
[self dismissViewControllerAnimated:YES];
}
else {
[self dismissViewControllerAnimated:YES];
}
}

in .h header file....
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#interface SimpleEmailViewController : UIViewController <MFMailComposeViewControllerDelegate> // Add the delegate
- (IBAction)showEmail:(id)sender;
#end
in .m implementation file.....
- (IBAction)showEmail:(id)sender {
// Email Subject
NSString *emailTitle = #"Test Email";
// Email Content
NSString *messageBody = #"iOS programming is so fun!";
// To address
NSArray *toRecipents = [NSArray arrayWithObject:#"info#finetechnosoft.in"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:NULL];
}
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled");
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved");
break;
case MFMailComposeResultSent:
NSLog(#"Mail sent");
break;
case MFMailComposeResultFailed:
NSLog(#"Mail sent failure: %#", [error localizedDescription]);
break;
default:
break;
}
// Close the Mail Interface
[self dismissViewControllerAnimated:YES completion:NULL];
}

Check if you are MFMailComposeViewControllerDelegate.
You do this like
#interface YouClassName : UIViewController <MFMailComposeViewControllerDelegate>
#end

I think you're using the wrong method. Try
[self presentViewController:(UIViewController *) animated:(BOOL) completion:(void)completion];
instead of:
[self presentViewController:composer animated:YES];

I work for Sendgrid. We have an Objective-c library that lets you quickly send email from inside your app, https://github.com/sendgrid/sendgrid-objc. You can use cocoapods to quickly install the library in your project.
Then sending the email from your (IBAction) would look like this:
-(IBAction)sendEmail{
sendgrid *msg = [sendgrid user:#"username" andPass:#"password"];
msg.to = #"FrankMurphy.CEO#RomansXIII.com";
msg.from = #"me#bar.com";
msg.text = #"hello world";
msg.html = #"<h1>hello world!</h1>";
[msg sendWithWeb];
}

Related

MFMailComposeViewController delegate not called

I'm not able to call Mail composer delegate method even if I'm writing below code:
-(void)openMailComposerInViewController:(UIViewController *)hostController{
if ([MFMailComposeViewController canSendMail])
{
// Email Subject
NSString *emailTitle = #"Test Email";
// Email Content
NSString *messageBody = #"Test Email";
// To address
NSArray *toRecipents = [NSArray arrayWithObject:#"support#test.com"];
mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
[mailComposer setSubject:emailTitle];
[mailComposer setMessageBody:messageBody isHTML:NO];
[mailComposer setToRecipients:toRecipents];
// Present mail view controller on screen
[hostController presentViewController:mailComposer animated:YES completion:NULL];
mailController = hostController;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Your device doesn't support the composer sheet"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
pragma mark - Mail
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled");
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved");
break;
case MFMailComposeResultSent:
NSLog(#"Mail sent");
break;
case MFMailComposeResultFailed:
NSLog(#"Mail sent failure: %#", [error localizedDescription]);
break;
default:
break;
}
// Close the Mail Interface
[mailController dismissViewControllerAnimated:YES completion:NULL];
}
I do not want to call mail composer on self
However, my delegate is not getting called. Please help. The application crashed on clicking on Cancel or Send mail button
I experienced this problem, and my problem was I had the following code:
self.mailComposer.mailComposeDelegate = self
self.mailComposer = MFMailComposeViewController()
I was setting the delegate before I initialized the mailComposer object. I just switched those 2 lines to this and it worked:
self.mailComposer = MFMailComposeViewController()
self.mailComposer.mailComposeDelegate = self
Because of ARC, I was losing the viewcontroller in which the delegate was written so it was not gettting called. Below code helped me fix the issue:
+(MailComposer *)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMailComposer = [[MailComposer alloc]init];
});
return sharedMailComposer;
}
Then I used the above instance while calling the MailComposerViewController
[[MailComposer sharedInstance] openMailComposerInViewController:[(UINavigationController *)moduleRouter.container topViewController]];
It Worked :)
your class instance must be same for setMailComposeDelegate and presentViewController.
mailComposer.mailComposeDelegate = hostController;
[hostController presentViewController:mailComposer animated:YES completion:nil];

How to send email in Xcode with Version 6.2?

I have looked at various tutorials for sending email in an app using Xcode, but most of the tutorials I have tried will not work for the current version of Xcode 6.2. When I run the IOS simulator, the email view will either instantly disappear or I can't type anything in any of the fields. I made sure to update the framework to use the MessageUI.framework. I will also post the current code I am using for the app. I want to use objective C as the language, as the app I am creating is using Objective C. Does anyone know how I can implement email in the current version(6.2)?
.h file
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#interface IntakeViewController : UIViewController <MFMailComposeViewControllerDelegate>{
}
- (IBAction)emailClicked:(id)sender;
#end
.m file
#import "IntakeViewController.h"
#interface IntakeViewController ()
#end
#implementation IntakeViewController
- (IBAction)emailClicked:(id)sender {
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc]init];
mail.mailComposeDelegate = self;
[mail setSubject:#"Review"];
NSArray *toRecipients = [NSArray arrayWithObjects:#"cbailey92#gmail.com", nil];
[mail setToRecipients:toRecipients];
NSString *body = #"You need more passion";
[mail setMessageBody:body isHTML:NO];
mail.modalPresentationStyle = UIModalPresentationPageSheet;
[self presentViewController:mail animated:YES completion:nil];
} else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Run Away!" message:#"You need more passion" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
}
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result) {
case MFMailComposeResultCancelled:
NSLog(#"Cancelled");
break;
case MFMailComposeResultSaved:
NSLog(#"Saved");
break;
case MFMailComposeResultFailed:
NSLog(#"Failed");
break;
case MFMailComposeResultSent:
NSLog(#"Sent");
break;
default:
NSLog(#"Default");
break;
}
[self dismissViewControllerAnimated:YES completion:nil];
}

how to compose mail when button at index clicked in UIActionSheet?

I am a bit confused on how to display mail composer when I click the email option in UIActionSheet.
Here's my sample code:
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if(buttonIndex == 0)
{
NSString *emailTitle = #"Test Email";
NSString *messageBody = #"iOS programming is so fun!";
NSArray *toRecipents = [NSArray arrayWithObject:#"support#email.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
[self presentViewController:mc animated:YES completion:NULL];
}
}
Make sure you add to your .h file and import the MessageUI.framework
Here is exactly what your looking for. I use this often. By the way UIActionSheets are deprecated in iOS 8. Here you go though:
.h
ViewController : UIViewController <MFMailComposeViewControllerDelegate>
.m
- (IBAction)showActionSheet:(id)sender {
UIActionSheet *moreActions = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Add To Favorites", #"Search",#"Email", nil];
[moreActions showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 0: [self addToFav:self];
break;
case 1: ; [self popSearchBar:self];
break;
case 2: { [self sendEmail];
break;
}
break;
}
}
- (void)sendEmail {
NSString *emailTitle = #"This is email title";
// Email Content as for HTML
NSString *messageBody = [NSString stringWithFormat:#"I may have found a missing document in your catalog. I tried opening :<p><strong><font color=\"red\"> %# </font><br>'%#'</strong></p> with no results. Can I have a dollar for reporting this?", self.title, self.titleString];
// To address
NSArray *toRecipents = [NSArray arrayWithObject:#"youremail#google.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:YES];
[mc setToRecipients:toRecipents];
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:NULL];
}
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult: (MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled");
[self dismissViewControllerAnimated:YES completion:NULL];
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved");
[self dismissViewControllerAnimated:YES completion:NULL];
break;
case MFMailComposeResultSent:
NSLog(#"Mail sent");
[self dismissViewControllerAnimated:YES completion:NULL];
break;
case MFMailComposeResultFailed:
NSLog(#"Mail sent failure: %#", [error localizedDescription]);
break;
default:
break;
}
// Close the Mail Interface
[self dismissViewControllerAnimated:YES completion:NULL];
}
Also note that some people are having issues with simulator emails. try it on a device before you give up.
Here's the code:
First add and import the message framework:
#import <MessageUI/MessageUI.h>
then mark your self as a delegate like this
#interface MYViewController () <MFMailComposeViewControllerDelegate>
then to pull up the composer:
- (IBAction)emailButtonPressed:(id)sender
{
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *composeViewController = [[MFMailComposeViewController alloc] initWithNibName:nil bundle:nil];
[composeViewController setMailComposeDelegate:self];
[composeViewController setToRecipients:#[#"example#email.com"]];
[composeViewController setSubject:#"example subject"];
[self presentViewController:composeViewController animated:YES completion:nil];
}
}
Then to handle the delegate callback and dismiss the composer:
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
//Add an alert in case of failure
[self dismissViewControllerAnimated:YES completion:nil];
}
in actionsheet using actionSheet: clickedButtonAtIndex:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
//Get the name of the current pressed button
NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
if ([buttonTitle isEqualToString:#"Your button title"]) {
[self btnContact];
}
}
call this method
- (void)btnContact{
// Email Subject
NSString *emailTitle = #"";
// Email Content
NSString *messageBody = #"";
// To address
NSString *toRecp = #"";
NSArray *toRecipents = [NSArray arrayWithObject:toRecp];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:NULL];
}
This is appcoda's code . Instead of index use the button's name to fire your mail option .

How to attach a PDF file to mail and send mail in iOS

Currently I am developing an expense management app and I want to attach a PDF file to the mail and send it to the specified email Address. So guide me from where should I start this and how to develop it.
Thanks.
MFMailComposeViewController *vc = [[MFMailComposeViewController alloc] init];
vc.mailComposeDelegate = self;
[vc setSubject:#"Monthly Expense Report"];
[vc addAttachmentData:pdfData mimeType:#"application/pdf" fileName:[NSString stringWithFormat:#"%#.pdf",[arrOfExpenseDate objectAtIndex:1]]];
if ([MFMailComposeViewController canSendMail])
{
[self presentViewController:vc animated:YES completion:nil];
}
I have created a example for you on how to send an pdf attachment using MFMailComposeViewController. Following is the code :
#interface ViewController () <MFMailComposeViewControllerDelegate>
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (IBAction)compseEmail:(id)sender
{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *vc = [[MFMailComposeViewController alloc] init];
vc.mailComposeDelegate = self;
[vc setSubject:#"Monthly Expense Report"];
NSString *pdfPath = [[NSBundle mainBundle] pathForResource:#"ApacheInstallationSteps" ofType:#"pdf"];
NSData *pdfData = [NSData dataWithContentsOfFile:pdfPath];
[vc addAttachmentData:pdfData mimeType:#"application/pdf" fileName:#"ApacheInstallationSteps.pdf"];
[self presentViewController:vc animated:YES completion:nil];
}
else
{
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Alert!!!" message:#"Your device can't send emails." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Result: canceled");
break;
case MFMailComposeResultSaved:
NSLog(#"Result: saved");
break;
case MFMailComposeResultSent:
NSLog(#"Result: sent");
break;
case MFMailComposeResultFailed:
NSLog(#"Result: failed");
break;
default:
NSLog(#"Result: not sent");
break;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Make sure that you add MessageUI.framework. Following is the output.
To send a pdf or any other attahcment in mail using MFMailComposeViewController, you have to use:
[mc addAttachmentData:fileData mimeType:mimeType fileName:filename];
For more details, follow this tutorial.
You can also download the sample code given in this tutorial for better understanding.
Hope that helps.

MFMailComposeViewController black screen on iPad

I'm using cocos2d-x framework and I need to popup the mail when clicking button.
The code works fine on iphone5 (6.0), ipod touch 5(6.0):
MailSender.h
#interface MailSender : UIViewController <MFMailComposeViewControllerDelegate>
{
UIViewController *currentModalViewController;
}
-(void)sendMail:(const char *)subject receiver:(const char *)receiver;
#end
MailSender.mm
#import "MailSender.h"
#import "../cocos2dx/platform/ios/EAGLView.h"
#implementation MailSender
- (void)sendMail:(const char *)subject receiver:(const char *)receiver
{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:[NSString stringWithUTF8String:subject]];
NSArray *toRecipients = [NSArray arrayWithObject:[NSString stringWithFormat:#"%s", receiver]];
[mailer setToRecipients: toRecipients];
//NSString *emailBody = [NSString stringWithFormat:#"<p>This is a sample posting in iOS. My Score is %s!</p>",score];
NSString *emailBody = #"";
[mailer setMessageBody:emailBody isHTML:YES];
// only for iPad
// mailer.modalPresentationStyle = UIModalPresentationFormSheet;
UIViewController* rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
currentModalViewController = [UIViewController alloc];
[rootViewController.view addSubview:currentModalViewController.view];
[currentModalViewController presentViewController:mailer animated:true completion:nil];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Your device doesn't support the composer sheet"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
const char *message;
switch (result)
{
case MFMailComposeResultCancelled:
message = "Mail cancelled";
break;
case MFMailComposeResultSaved:
message = "Mail saved";
break;
case MFMailComposeResultSent:
message = "Mail send";
break;
case MFMailComposeResultFailed:
message = "Mail failed";
break;
default:
message = "Mail cancelled";
break;
}
NSLog(#"%s",message);
[currentModalViewController dismissViewControllerAnimated:true completion:nil];
[currentModalViewController.view.superview removeFromSuperview];
[currentModalViewController release];
}
#end
But on my ipad mini (6.0) the mail popped up correctly but when clicked the "send mail" or "cancel" the view was removed and leaving a black screen (everything on the screen is gone)
Any advice will be appreciated, thanks :)
try this code
if ([MFMailComposeViewController canSendMail]) {
mailComposer = [[MFMailComposeViewController alloc]init];
mailComposer.mailComposeDelegate = self;
[mailComposer setToRecipients:#[#"yourmail#com"]];
[mailComposer setSubject:#"Subject"];
[mailComposer setMessageBody:#"hello \n" isHTML:NO];
[self presentViewController:mailComposer animated:YES completion:nil];
}
else{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Error"
message:#"can not send mail with this device"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alert show];
}
pragma mark MFMailComposeViewControllerDelegate
-(void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
if (result) {
NSLog(#"Result : %d",result);
}
if (error) {
NSLog(#"Error : %#",error);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
I'm using this code for feedback via email in my cocos2d-x game.
Application::getInstance()->openURL("mailto:" + SUPPORT_EMAIL);
You can add subject:
Application::getInstance()->openURL("mailto:" + SUPPORT_EMAIL + "?subject=Hello from NX");
This solution tested on iOS and Android.

Resources