iPhone to use MFMailComposer to send email from app? - iphone

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.

Related

MFMailComposeViewController issue with From address

I send mail using following code:
- (IBAction)sendMailPressed:(id)sender
{
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];
}
}
// Displays an email composition interface inside the application. Populates all the Mail fields.
-(void)displayComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:self.strMailSubject];
// Attach pdf to the email
NSURL *urlToLoad = [[NSBundle mainBundle] URLForResource:self.strSorce withExtension:self.strExtention];
NSData *myData = [NSData dataWithContentsOfURL:urlToLoad];
[picker addAttachmentData:myData mimeType:#"application/pdf" fileName:[NSString stringWithFormat:#"%#.%#", self.strSorce, self.strExtention]];
// [self presentModalViewController:picker animated:YES];
[[Singleton sharedInstance] pushModalViewController:picker whereCurrentController:self animated:YES];
[picker release];
}
// 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
{
// Notifies users about errors associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:
break;
case MFMailComposeResultSaved:
break;
case MFMailComposeResultSent:
break;
case MFMailComposeResultFailed:
break;
default:
break;
}
[[Singleton sharedInstance] popModalViewControllerAnimated:YES];
}
// Launches the Mail application on the device.
-(void)launchMailAppOnDevice
{
NSString *recipients = [NSString stringWithFormat:#"mailto:&subject=%#", self.strMailSubject];
NSString *email = [NSString stringWithFormat:#"%#", recipients];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
And I get this view:
But I need this view (please, pay attention only to From string, not to the image).
I don't know how to make From string appear
You can use setCcRecipients: for this in your code.
just add this line in your displayComposerSheet method after create MFMailComposeViewController and also just set the NSArray with Recipients names...
NSString *strFullName = [NSString stringWithFormat:#"From : %#",yourSenderEmailAddress];/// here write your email address which dynamic get from your string
NSArray *arrRecipients = [[NSArray alloc]initWithObjects:strFullName, nil];
[picker setCcRecipients:arrRecipients];
I Update code with one example also...
Also Vishal's Answer is also right, i just complete it..
If more than one mail account have been added, the from field will be visible in order to select the sender from multiple accounts.
There isn't any way to set the From: field of MFMailComposeViewController programmatically, probably for security reasons. The owner of the device has control over what accounts are registered on the device and therefore what the From: field is allowed to contain.
The From: field only shows if multiple email accounts have been configured on the device; that field then allows the user to pick which account to send from. If only one account exists on the device, it is not shown (it "goes without saying" which account is being used).
You can use "setPreferredSendingEmailAddress" for iOS 11 and newer.

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)
}

iphone app send email

I know how to send an email within my app by launching the Mail app then returning to my app... but I would like to my app to be able to send email without opening the mail app.
For exemple i'd have a button in my app clicking that button would send out an email. I will then notify the user that the email has been sent...
Has anyone been doing this ?
thanks.
Sami
Here is a sample code to send email using MFMailComposeViewController.
-(IBAction)showPicker:(id)sender {
// This sample can run on devices running iPhone OS 2.0 or later
// The MFMailComposeViewController class is only available in iPhone OS 3.0 or later.
// So, we must verify the existence of the above class and provide a workaround for devices running
// earlier versions of the iPhone OS.
// We display an email composition interface if MFMailComposeViewController exists and the device can send emails.
// We launch the Mail application on the device, otherwise.
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];
}
}
-(void)displayComposerSheet {
// Displays an email composition interface inside the application. Populates all the Mail fields.
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Hello from California!"];
// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:#"first#example.com"];
NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
NSArray *bccRecipients = [NSArray arrayWithObject:#"fourth#example.com"];
[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];
// Attach an image to the email
NSString *path = [[NSBundle mainBundle] pathForResource:#"rainy" ofType:#"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"rainy"];
// Fill out the email body text
NSString *emailBody = #"It is raining in sunny California!";
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
message.hidden = NO;
// 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];
}
-(void)launchMailAppOnDevice {
// Launches the Mail application on the device.
NSString *recipients = #"mailto:first#example.com?cc=second#example.com,third#example.com&subject=Hello from California!";
NSString *body = #"&body=It is raining in sunny California!";
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
You have a few choices. You can use Apple's MFMailComposeViewController class (see below) which allows you to make a message in your app and pass it to iPhone's Mail, without launching the Mail app or leaving yours. You can also implement SMTP in your app to send e-mail directly. You can also hand off your email to a webserver and have the webserver send it out. The easiest is the first way. The drawback is that you don't really know if the message was sent out or not, which depends on whether the network was operational or not and other factors. Of course, if you go with your own SMTP code, you will have to handle all the queuing and retrying in case the network, or server is unavailable, and that means your app has to be running in order to do that.
From Apple's docs:
The MFMailComposeViewController class provides a standard interface that manages the editing and sending an email message. You can use this view controller to display a standard email view inside your application and populate the fields of that view with initial values, such as the subject, email recipients, body text, and attachments. The user can edit the initial contents you specify and choose to send the email or cancel the operation.
The best way to do this is to have a webserver for your app that does the mail sending. You'd pass along the details of the e-mail and have your server send it on the user's behalf.
Add framework in buildphases MessageUI.framework
ViewController.h file
#import <MessageUI/MessageUI.h>
#interface ViewController () <MFMailComposeViewControllerDelegate>
ViewController.m file
-(IBAction)emailButtonClicked:(id)sender{
MFMailComposeViewController *mailComposer =[[MFMailComposeViewController alloc] init];
if (mailComposer !=nil) {
mailComposer.mailComposeDelegate = self;
NSString *emailBody = #"Write the text here........";
[mailComposer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailComposer animated:YES];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self becomeFirstResponder];
[self dismissModalViewControllerAnimated:YES];
}