Unable to send email using MFMailComposeViewController in simulator - ios

I am new to ios app development, Below is the code I used to send an email.
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"My Subject"];
[controller setMessageBody:#"Hello there." isHTML:NO];
[self presentModalViewController:controller animated:YES];
[controller release];
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error {
if (result == MFMailComposeResultSent) {
NSLog(#"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
Unfortunately delegate methods are never triggered , Can any one please suggest how can i check my email via simulator?

You CANNOT send mails through Simulator.
Instead you can install the application in device and try from there.
Simulator just displays the composer but wont allow you to send mails. Sent Successfully is just the acknowledgment that your code is fine and there is no issue that terminates it while sending.

As far as i know, you cannot send mail from Simulator.. The MFMailComposeViewController uses the mailbox configured in iPhone's Mail app to send the mail. The simulator does not have the Mail app.

You can able to send mail using the Gmail connectivity you can send mail to user for that you need to insert the some amount of code and setting in your code following code which use for sending a mail.
- (IBAction)sendMessageInBack:(id)anObject{
NSLog(#"Start Sending");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"sample.pdf"];
NSData *dataObj = [NSData dataWithContentsOfFile:writableDBPath];
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = #"Your mail id";
testMsg.toEmail = #"sender mail ids";
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"Uour mail id";
testMsg.pass = #"your pass";
testMsg.subject = #"Test application ";
testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!
// Only do this for self-signed certs!
// testMsg.validateSSLChain = NO;
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
#"Some text to include in body",kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
}
-(void)messageSent:(SKPSMTPMessage *)message{
[message release];
NSLog(#"delegate - message sent");
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
[message release];
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable to send email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
And following files copy into your project.
For downloading a sample code here.

Related

In app email pop up not working for iOS 8 in Xcode 6

The email popup is not working in iOS 8 (Xcode 6). This popup is working fine in iOS 7 (Xcode 5). This pop up never works on simulator and on the device sometimes it works and sometimes it doesn't. Also I have seen the case that when i debug and execute each lines on debugging mode, it works but not so when I directly execute. Here's the code for MFMailComposerViewController inside the emailButtonPressed() method. Please suggest how can i solve this issue.
- (IBAction)emailButtonPressed:(id)sender {
if([MFMailComposeViewController canSendMail] == NO)
{
//Mail not configured correctly
CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(#"Email", #"HDR") message:NSLocalizedString(#"Email is not Configured", #"INF") delegate:nil cancelButtonTitle:NSLocalizedString(#"Ok", #"BTN") otherButtonTitles: nil];
[alert show];
return;
}
[[NSNotificationCenter defaultCenter] postNotificationName:kShowBusyIndicatoryEventName object:self];
MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
mailPicker.mailComposeDelegate = self;
[mailPicker setSubject:#""];
// Set up recipients
NSString *emailBody = #" ";
NSString *fileName = #" ";
[mailPicker setMessageBody:emailBody isHTML:NO];
mailPicker.navigationBar.tintColor = [UIColor colorWithRed:0.16 green:0.16 blue:0.16 alpha:1.0];
UIViewController *viewToCreate = [self.delegate viewControllerForPDF:self];
// set attachment file name and subject
if(viewToCreate)
{
if([viewToCreate isKindOfClass:[PDFPlaceOrderFinalizeViewController class]])
{
PDFPlaceOrderFinalizeViewController *pdfViewController = (PDFPlaceOrderFinalizeViewController *)viewToCreate;
if(pdfViewController.showPendingOrderView)
{
fileName = NSLocalizedString(#"Quote.pdf", "PDF");
}
else
{
fileName = NSLocalizedString(#"Order.pdf", "PDF");
}
[mailPicker setSubject:pdfViewController.emailSubject];
}
else if([viewToCreate isKindOfClass:[PDFOrderGuideViewController class]])
{
PDFOrderGuideViewController *pdfViewController = (PDFOrderGuideViewController *)viewToCreate;
fileName = NSLocalizedString(#"OrderGuide.pdf", "PDF");
[mailPicker setSubject:pdfViewController.emailSubject];
}
NSData *data= [self createPDFfromUIView:viewToCreate];
[mailPicker addAttachmentData:data mimeType:#"application/pdf" fileName:fileName];
}
[self presentModalViewController:mailPicker animated:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:kHideBusyIndicatoryEventName object:self];
[self.delegate dismissPopOver];
}

how to use Gmail smtp in iOS app

I am new to Xcode I need an app to send a email. Background: the destination email Id is typed in a text and by clicking the send button the message body Sample should go to the destination Email ID I tried this code in the function button clicked but it is not working when ever i try this code I get error in function can any one guide me with a step by step tutorial
mailTransfer[673:207] delegate - error(-5): timeout sending message
2014-07-05 10:54:05.393 mailTransfer[673:207] * stopping watchdog * I had added the SMTP files from google documents ... any other way to correct this code
- (IBAction)sendMessageInBack:(id)anObject
{
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = #"Yours mail ids";
testMsg.toEmail = emailField.text;
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"Your mail ids";
testMsg.pass = #"id password";
testMsg.subject = #"Test application ";
testMsg.wantsSecure = YES;
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionarydictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,#"Sample",kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
}
-(void)messageSent:(SKPSMTPMessage *)message{
[message release];
NSLog(#"delegate - message sent");
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
[message release];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable to send email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
in SKPSMTPMessage.m
update the following line
CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);
with
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);
Download SMTP framework and import SKPSMTPMessage class..
#import "SKPSMTPMessage.h"
-(void)sendEmailVideo:(NSString*)_toEmailAddress andCC:(NSString*)ccEmail
{
#try
{
// Message =[data getContentOfPanic];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail=#"nikki.varsha#gmail.com";//sender email address
emailMessage.toEmail=_toEmailAddress;
//receiver email address
emailMessage.relayHost=#"smtp.gmail.com";
//emailMessage.ccEmail =ccEmail;
emailMessage.requiresAuth = YES;
emailMessage.login = #"nikki.varsha#gmail.com"; //sender email address
emailMessage.pass = #"123";
//sender email password
emailMessage.subject =#"Panic Video Message";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
Message,kSKPSMTPPartMessageKey,#"8bit", kSKPSMTPPartContentTransferEncodingKey,nil];
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"Video.mov\"",kSKPSMTPPartContentTypeKey,
#"attachment;\r\n\tfilename=\"Video.mov\"",kSKPSMTPPartContentDispositionKey,[webData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts=[NSArray arrayWithObjects:plainPart,vcfPart,nil];
dispatch_queue_t backgroundVideoQueue = dispatch_queue_create("com.VideoQue", 0);
dispatch_sync(backgroundVideoQueue, ^{
[emailMessage send];
});
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Host" message:#"No Reciever Email Ids Available! " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
pragma mark - sendEmail delegate (SKPSMTPMessage)
-(void)messageSent:(SKPSMTPMessage *)message
{
NSLog(#"delegate - Email sent");
NSLog(#"Mesg %#",message);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Email sent." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"err=%#" ,message);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Unable to send email Please Check EmailId & Password"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
});
}
in SKPSMTPMessage.m file do change the following line
Remove this line
//CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);
Add this line
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);
Thanks

in-app email makes swoosh sound but doesn't send

I get to the Mail program fine, and when I press "Send" I hear the swoosh sound and Mail closes and returns me to my app, but the actual mail isn't sending.
Here's the code I'm using to mail. Any ideas about what I'm doing wrong?
(I'm using iOS6, on an actual device, not the simulator.)
-(void)openMail {
//Open Mail program and create email with haiku attached as image.
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:[NSString stringWithFormat:#"subject"]];
UIImage *myImage = [self createImage];
NSData *imageData = UIImagePNGRepresentation(myImage);
[mailer addAttachmentData:imageData mimeType:#"image/jpg" fileName:#"xxxxx"];
NSString *emailBody = #"I thought you might like this haiku from the xxxxx iPhone app.";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentViewController:mailer animated:YES completion:NULL];
}
//Unless it's not possible to do so, in which case show an alert message.
else
{
self.alert = [[UIAlertView alloc] initWithTitle:#"I'm sorry." message:#"Your device doesn't seem to be able to email this haiku. Perhaps you'd like to tweet it or post it on Facebook instead?" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[self.alert show];
}
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
[self dismissViewControllerAnimated:YES completion:Nil];
}
It looks like it's actually a problem between my server and the iOS 6.1 update. I'll leave this up in case other people have the same problem. If the issue is fixed and my email STILL won't send, then I'll post another question.

Cannot send email in app using MFMailComposeViewController

I have an app which uses MFMailComposeViewController to send documents through email. I read somewhere that I need to enable at least one email so that the method [MFMailComposeViewController canSendEmail] will return YES and email the document. However, whenever I tap the email button, all it does is return to the previous view.
I checked the code and [MFMailComposeViewController canSendEmail] returns NO. Can anyone tell me why is this happening?
Here is the code:
- (void)sendEmail
{
if ([MFMailComposeViewController canSendMail] == NO) return;
NSURL *fileURL = document.fileURL; NSString *fileName = document.fileName;
NSData *attachment = [NSData dataWithContentsOfURL:fileURL options:(NSDataReadingMapped|NSDataReadingUncached) error:nil];
if (attachment != nil)
{
MFMailComposeViewController *mailComposer = [MFMailComposeViewController new];
[mailComposer addAttachmentData:attachment mimeType:#"application/pdf" fileName:fileName];
[mailComposer setSubject:fileName];
mailComposer.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
mailComposer.modalPresentationStyle = UIModalPresentationFormSheet;
mailComposer.mailComposeDelegate = self;
[self presentModalViewController:mailComposer animated:YES];
[mailComposer release];
}
}
First add and Import the MessageUI Framework
#import <MessageUI/MessageUI.h>
and Declare the MFMaileComposeViewControllerDelegate
#interface MailViewController : UIViewController <MFMailComposeViewControllerDelegate>
Write this code for sending the mail
- (IBAction)openMail:(id)sender
{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"xyz"];
NSArray *toRecipients = [NSArray arrayWithObjects:#"fisrtMail#example.com", #"secondMail#example.com", nil];
[mailer setToRecipients:toRecipients];
NSData *pdfdata = [NSData dataWithContentsOfURL:"Your URL"]
[mailController addAttachmentData:pdfData
mimeType:#"application/pdf"
fileName:#"file.pdf"];
NSString *emailBody = #"xyz";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
[mailer release];
}
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];
}
}
and also write the delegate method of MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled: you cancelled the operation and no email message was queued.");
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved: you saved the email message in the drafts folder.");
break;
case MFMailComposeResultSent:
NSLog(#"Mail send: the email message is queued in the outbox. It is ready to send.");
break;
case MFMailComposeResultFailed:
NSLog(#"Mail failed: the email message was not saved or queued, possibly due to an error.");
break;
default:
NSLog(#"Mail not sent.");
break;
}
// Remove the mail view
[self dismissModalViewControllerAnimated:YES];
}
because your mail app in iphone not auth. Go to preferences -> Mail (or simply open Mail app) and auth from google or another service and you can sent emails through MFMailComposeViewController. (this in on real iPhone - I don't try it on simulator)

Send Contact Form Fields in Email

I have a contact form made of text fields (5 fields) that I would like to send via email to a single email address. How do I do this in xCode?
For anyone stumbling across this question, you can use this drop-in iOS contact form.
This fit my needs well, it uses a PHP component to actually send the email. (an example script is included in the sample project.
I posted it to Github here:
https://github.com/mikecheckDev/MDContactForm
The linked post has a similar answer, but I'm adding my code since it checks for canSendMail already. I also left in a bunch of commented code that makes it easy to add other stuff to the email.
Note that this is substantially easier if you are only targeting iOS 5.
I have a free app, QCount, that uses this code. Indeed, I hope I stripped everything custom from my copy-and-paste :-) http://itunes.apple.com/ng/app/qcount/id480084223?mt=8
Enjoy,
Damien
In your .h:
#import <MessageUI/MessageUI.h>
Methods in your .m:
- (void)emailLabelPressed { // or whatever invokes your email
// Create a mail message in the user's preferred mail client
// by opening a mailto URL. The extended mailto URL format
// is documented by RFC 2368 and is supported by Mail.app
// and other modern mail clients.
//
// This routine's prototype makes it easy to connect it as
// the action of a user interface object in Interface Builder.
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 {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Your Form Subject"];
// Take screenshot and attach (optional, obv.)
UIImage *aScreenshot = [self screenshot];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(aScreenshot)];
[picker addAttachmentData:imageData mimeType:#"image/png" fileName:#"screenshot"];
// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:#"first#example.com", nil];
// NSArray *ccRecipients = [[NSArray alloc] init];
// NSArray *bccRecipients = [[NSArray alloc] init];
// NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
// NSArray *bccRecipients = [NSArray arrayWithObjects:#"fourth#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 = #"Use this for fixed content.";
NSMutableString *emailBody = [[NSMutableString alloc] init];
[emailBody setString: #"Feedback"];
// programmatically add your 5 fields of content here.
[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
if ([self respondsToSelector:#selector(presentViewController:animated:completion:)]) {
[self presentViewController:picker animated:YES completion:nil];
} else {
[self presentModalViewController:picker animated:YES];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
if ([self respondsToSelector:#selector(dismissViewControllerAnimated:completion:)]) {
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self dismissModalViewControllerAnimated:YES];
}
}
-(void)launchMailAppOnDevice {
NSString *recipients = #"mailto:first#example.com?cc=second#example.com,third#example.com&subject=Hello from California!";
NSString *body = #"&body=Feedback";
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

Resources