Show System Alert "No Mail Accounts" - iphone

Currently I am using [MFMailComposeViewController canSendMail] to check if there exists some Account in Device. If Not I wish to show some Alert.
I saw an app of same kind which gives the alert "No Mail Accounts" in Localized Language.
I want the same Alert which should also be localized.
Is it some system Alert Or Will I have to create a custom with all localization strings?
Here is the exact implementation I am using
if (![MFMailComposeViewController canSendMail])
return nil;
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
if(mailViewController)
{
//Setting Email Stuff
}

It's a system message, so you don't have to localize it, it will be displayed in the correct language if your project contains that language
Class mailClass = (NSClassFromString(#"MFMailComposeViewController"));
if (mailClass != nil)
{
MFMailComposeViewController *vc = [[[MFMailComposeViewController alloc] init] autorelease];
if (vc!=nil) {
[vc setSubject:#"Mail subject"];
NSMutableString * message = #"mail message";
[vc setMessageBody:message isHTML:YES];
vc.mailComposeDelegate = self;
[self presentModalViewController:vc animated:YES];
}
}
else
{
//Device doesn't include mail class, so it can't send mails
}
Don't check the canSendMail and the device will show the no accounts alert when you try to send the message

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.

Email issue: want to send email without additional window

I want to send email without showing MFMailComposeViewController. I just want to send email to some sequence of emails (so user should see only my spinner, not MFMailComposeViewController with send button).
The only way to send emails I know is: (but it's not I want)
-(void)showMessageController:(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];
[appDelegate setNavigationBarTextured:YES navigationBar:picker.navigationBar];
picker.mailComposeDelegate = self;
[picker setSubject:#"Please, look at my photo!"];
// Attach an image to the email (mydata - data of the image)
[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"photo"];
// Fill out the email body text
NSString *emailBody = #"Hello!\nPlease, have a look at my photo!";
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];
}
// Launches the Mail application on the device.
-(void)launchMailAppOnDevice
{
// NSString *recipients = #"mailto:first#example.com?cc=second#example.com,third#example.com&subject=Hello from California!";
NSString *recipients = #"mailto:subject=Please, look at my photo!";
NSString *body = #"&body=Hello!\nPlease, have a look at my photo!";
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
How can I send email without additional screen of MFMailComposeViewController?
Thank you in advance!
You can do it by Web services. Write a web service that takes message for Email body and receiver's email address, subject etc as parameters and sends mail from backend.
You can create PHP script to send email and can call the php service call with To, Message, Subject passed from device,
There is no API provided by Apple that would let you send emails without user interaction.

iPhone SMS Url Scheme with Body Content?

I am looking to pre-fill the SMS body with content given "smsto:555-555-5555:Hello World"
I have done my research and everybody says it cannot be done but I have a QR reader on my phone right now that can take "sms:555-555-5555:Hello world" and pre-fills the content with the correct phone number scanned.
So my question is. How do i do this? it is pretty clear that the URL scheme provided doesn't handle the body. What other methods are out there to pre-fill the body? it can clearly be done with the QuickMark Reader.
You can use the modalViewController for SMS to fill the body of a text.
add the MessageUI framework to your project.
set you viewController as the MFMessageComposeDelegate
Create the modal view and present it:
-(void) showMessageComposerWithText:(NSString*)messageText telNumber:(NSString*)telNumber composeDelegate:(id)delegate
{
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
if([MFMessageComposeViewController canSendText]){
controller.body = messageText;
controller.recipients = [NSArray arrayWithObject:telNumber];
controller.messageComposeDelegate = delegate;
[delegate presentModalViewController:controller animated:YES];
}
}
You can't launch the Messages app with a predefined message according to Apple Documentation.
What you can do is implement the handling yourself and parse the URL like the following:
NSURL *url = /* the url you get from the web (in webview delegate) or after QR Code scan */;
if ([url.scheme isEqualToString:#"sms"]) // is it a sms ?
{
if([MFMessageComposeViewController canSendText]) // can I send text message ?
{
NSArray *parts = [url.absoluteString componentsSeparatedByString:#":"];
NSString *messageText = parts.count == 3 ? [parts objectAtIndex:2] : #"";
NSString *telNumber = parts.count >= 2 ? [parts objectAtIndex:1] : #"";
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
controller.body = messageText;
controller.recipients = [NSArray arrayWithObject:telNumber];
controller.messageComposeDelegate = self;
[self presentViewController:controller animated:YES completion:nil];
[controller release];
}
}
And voilĂ  !

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];
}