Send Email from TableView in ViewController - ios

I have a TableView set to trigger a different ViewController when the user selects an item in the list, but I would like "Contact Us" to trigger the Messages Framework (In App Email) so the user can send an email and not get pushed to a ViewController.
Any suggestions? Below is a block of code that I'm using for "Contact Us".
Sorry if this is an obvious answer, learning as I go and envy all you wizards out there!
NSMutableDictionary *sectionContactUs = [NSMutableDictionary dictionary];
[sectionContactUs setObject:kSlideViewControllerSectionTitleNoTitle forKey:kSlideViewControllerSectionTitleKey];
[sectionContactUs setObject:#"Contact Us" forKey:kSlideViewControllerSectionTitleKey];
NSMutableDictionary *contactUsViewControllerDictionary = [NSMutableDictionary dictionary];
[contactUsViewControllerDictionary setObject:#"Contact Us" forKey:kSlideViewControllerViewControllerTitleKey];
[contactUsViewControllerDictionary setObject:#"ContactUsViewController" forKey:kSlideViewControllerViewControllerNibNameKey];
[contactUsViewControllerDictionary setObject:[ContactUsViewController class] forKey:kSlideViewControllerViewControllerClassKey];
[sectionTest setObject:[NSArray arrayWithObject:contactUsViewControllerDictionary] forKey:kSlideViewControllerSectionViewControllersKey];
[datasource addObject:sectionContactUs];

Use MFMailComposeComposeView:
First Import MessageUI framework in your project
And write #import <MessageUI/MessageUI.h> in your view controller also add MFMailComposeViewControllerDelegate at interface
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
NSArray *toRecipients = [NSArray arrayWithObjects:#"test1#gmail.com", #"test2#gmail.com", nil];
[controller setToRecipients:toRecipients];
[controller setTitle:#"Contact Us"];
[controller setSubject:#"Your Mail Subject"];
[controller setMessageBody:#"Mail body here \n Comments" isHTML:NO];
if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)
{
controller.modalPresentationStyle = UIModalPresentationFormSheet;
}
else
{
controller.modalPresentationStyle = UIModalPresentationFullScreen;
}
[self presentModalViewController:controller animated:YES];
Also add this methods
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self becomeFirstResponder];
NSString *strMailResult;
switch (result)
{
case MFMailComposeResultCancelled:
strMailResult = NSLocalizedString(#"E-Mail Cancelled",#"");
break;
case MFMailComposeResultSaved:
strMailResult = NSLocalizedString(#"E-Mail Saved",#"");
break;
case MFMailComposeResultSent:
strMailResult = NSLocalizedString(#"E-Mail Sent",#"");
break;
case MFMailComposeResultFailed:
strMailResult = NSLocalizedString(#"E-Mail Failed",#"");
break;
default:
strMailResult = NSLocalizedString(#"E-Mail Not Sent",#"");
break;
}
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Message",#"") message:strMailResult delegate:self cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alertView show];
[self dismissModalViewControllerAnimated:YES];
}

you can open MFMailComposeViewController for send mail..
-(void)doEmail
{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate =self;
[picker setMessageBody:#"Body message" isHTML:NO];
[self presentModalViewController:picker animated:YES];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[self dismissModalViewControllerAnimated:YES];
//////nslog (#"mail finished");
}

Related

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 can I share a string through email and imessage from my iOS app?

My webview opens up a specific URL, and I have it set up where if a user taps the search button, the following dialogue appears:
How do I allow a user to share the url string when they tap each respective button? This is what I have so far:
- (IBAction)shareButtonAction:(id)sender {
UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:#"Select Sharing option:" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:
#"Share via E-mail",
#"Share via iMessage",
nil];
popup.tag = 1;
[popup showInView:[UIApplication sharedApplication].keyWindow];
}
- (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (popup.tag) {
case 1: {
switch (buttonIndex) {
case 0:
NSLog(#"lets share on email");
break;
case 1:
NSLog(#"lets share on iMessage");
break;
default:
break;
}
break;
}
default:
break;
}
}
Sharing by email and message is using the same framework, these is the steps:
Add the framework MessageUI into your project.
Import the header in your class: #import <MessageUI/MessageUI.h>
Implements the sharing code
Use MFMailComposeViewController to share by email:
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
[mailController setMailComposeDelegate:self];
[mailController setSubject:#"Your subject"];
[mailController setToRecipients:#[#"email1", #"email2"];
[mailController setMessageBody:#"Your body" isHTML:NO];
[self presentViewController:mailController animated:YES completion:nil];
}
// Then implement the delegate method
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissViewControllerAnimated:YES completion:nil];
}
And MFMessageComposeViewController to share by message:
if ([MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init];
[messageController setMessageComposeDelegate:self];
[messageController setRecipients:[NSArray arrayWithObject:#"recipient"]];
[messageController setBody:#"Your body"];
[self presentViewController:messageController animated:NO completion:nil];
}
// Then implement the delegate method
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
[self dismissViewControllerAnimated:YES completion:nil];
}

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.

How to send email with UITableView

So I'm using this array to display email addresses in a custom table cell
EmailAddress = [NSArray arrayWithObjects:#"sample#aths.ac.ae",:#"sample#aths.ac.ae",:#"sample#aths.ac.ae", :#"sample#aths.ac.ae",:#"sample#aths.ac.ae",:#"sample#aths.ac.ae", nil];
and I used this code for my email but I always get a SIGABRT error whenever I press the cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
NSArray *toRecipients = [EmailAddress objectAtIndex:indexPath.row];
[controller setToRecipients:toRecipients];
[controller setTitle:#""];
[controller setSubject:#""];
[controller setMessageBody:#"" isHTML:NO];
if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)
{
controller.modalPresentationStyle = UIModalPresentationFormSheet;
}
else
{
controller.modalPresentationStyle = UIModalPresentationFullScreen;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self becomeFirstResponder];
NSString *strMailResult;
switch (result)
{
case MFMailComposeResultCancelled:
strMailResult = NSLocalizedString(#"E-Mail Cancelled",#"");
break;
case MFMailComposeResultSaved:
strMailResult = NSLocalizedString(#"E-Mail Saved",#"");
break;
case MFMailComposeResultSent:
strMailResult = NSLocalizedString(#"E-Mail Sent",#"");
break;
case MFMailComposeResultFailed:
strMailResult = NSLocalizedString(#"E-Mail Failed",#"");
break;
default:
strMailResult = NSLocalizedString(#"E-Mail Not Sent",#"");
break;
}
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Message",#"") message:strMailResult delegate:self cancelButtonTitle:NSLocalizedString(#"OK",#"") otherButtonTitles:nil];
[alertView show];
[self dismissViewControllerAnimated:YES completion:nil];
}
but I end up with the error I think the error is from the toRecipient but I dont know how to fix it.
One obvious problem is with the following two lines:
NSArray *toRecipients = [EmailAddress objectAtIndex:indexPath.row];
[controller setToRecipients:toRecipients];
It should be:
NSString *toRecipient = [EmailAddress objectAtIndex:indexPath.row];
[controller setToRecipients:#[ toRecipient ]];
since you only get a single recipient value from the EmailAddress array.

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