How to get value from UITextfield and sent it to email? - iphone

I've created an app which contains form and that have to filled up in appropiate text fields..now i need to get all data in textfield and it to be sent in email.here is my code for composing email
- (IBAction)compose:(id)sender
{
if (text1.text=#"" && text2.text=#"" && text3.text=#"" && text4.text=#"" && text5.text=#"") {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Please enter all the field details"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
}
else{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:[NSString stringWithFormat:#"Appointment From Mr/Mrs. %#",text1.text]];
NSArray *toRecipients = [NSArray arrayWithObjects:#"xxx#xxxx.com", nil];
[mailer setToRecipients:toRecipients];
NSString *emailBody =[NSString stringWithFormat:#"Name =%#\nDate= %#\nPreferred Time Slot= %#\nE-Mail=%#\nSpecific Requests=",text1.text,text2.text,text3.text,text4.text,text5.text];
[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];
}
}
}
if all the text field is null it have to popup an alert.But i'm getting error?...guide me pls..

If you are wondering how to get the text from textfield, and send it, you will need to use textfield.text
NSString *emailBody = textField.text;
[mailer setMessageBody:emailBody isHTML:NO];

There can be two way -
You can create proprty for your text field, and then access like - myTextField.text where you want.
You can create a NSString property and set value in to this when text field has some text.

//this is one single line which return your textFiledData
your_text_field.text

Create a variable for ur textfield like IBOutlet UITextField * textFieldVar; and connect it to ur Text field in the nib , then using the following code u can get the text from the text field
NSString *emailBody = textFieldVar.text;

You can create the body of email as you want by appending the string with particular format
Like
User ID: 223984775(value from the textfieldUserID)
Name: XYZ(value from the textfieldName)
......
You can do this by appending the string as the user moves to the next text field to enter.
Use Nsstring "stringWithFormat" method to append the data in the body. Use \n and \t to give a Tabular structure to the body of email. Use formatting too

Related

Trying to send email, getting "use of undeclared unidentified MFMailComposeViewController"

I'm trying to send a email message in my app. I'm trying to use the MFMailComposeViewController object, but getting a error message saying its a "undeclared identifier"
code:
-(IBAction) aContact: (id) sender;
{
if([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mailCtrl = [[[MFMailComposeViewController alloc] init] autorelease];
[mailCtrl setSubject:#"Your TellaFortune Card Reading"];
// [mailCtrl setToRecipients:[NSArray arrayWithObject:#"drblyer#cameosurgery.com"]];
mailCtrl.mailComposeDelegate = self;
NSString *send;
send=[ NSString stringWithFormat: #"%# %#",content,#"\n \n By www.TellaFortune.com"];
[mailCtrl setMessageBody: send isHTML: false];
[self presentModalViewController:mailCtrl animated:NO];
// [mailCtrl release];
}
else
{
UIAlertView *alert=[[ UIAlertView alloc]
initWithTitle:#"Cannot send email"
message: #"Please check internet connection and email set up"
delegate: self
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
[alert show];
}
}
Import framework "MessageUI.framework" to your project and in your .h file add
#import <MessageUI/MessageUI.h>
For anyone who is using Swift and seeing this message:
First go to your project settings in Xcode, select Build Phases, then Link Binary with Libraries, and add "MessageUI.framework" to your project.
Then, in the Swift file in which you want to use a MFMailComposeViewController or implement the MFMailComposeViewControllerDelegate, add:
import MessageUI

MessageUI framework issue for UITextField contents are not displayed

I've included messageUI framework in my app for sending mail.It contains five UITextField where the values entered by user should be displayed in mail body. Here is my code
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:[NSString stringWithFormat:#"Appointment From Mr/Mrs. %#",text1.text]];
NSArray *toRecipients = [NSArray arrayWithObjects:#"info#xxx.com", nil];
[mailer setToRecipients:toRecipients];
NSString *emailBody =[NSString stringWithFormat:#"Name :%#\nDate: %#\nPreferred Time Slot: %#\nE-Mail:%#\nSpecific Requests:",text1.text,text2.text,text3.text,text4.text,text5.text];
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
[mailer release];
}
The issue i'm facing is that all the four text field values are displayed only the fifth text field values are not displayed..Any idea?...am i missing anything?...
You only have four %# in the form at string, thus the last parameter supplied to the format method is ignored.
Change the format string to have five parameters:
NSString *emailBody =[NSString stringWithFormat:#"Name :%#\nDate: %#\nPreferred Time Slot: %#\nE-Mail:%#\nSpecific Requests:%2",text1.text,text2.text,text3.text,text4.text,text5.text];
Edit the following line of code
NSString *emailBody =[NSString stringWithFormat:#"Name :%#\nDate: %#\nPreferred Time Slot: %#\nE-Mail:%#\nSpecific Requests:%#",text1.text,text2.text,text3.text,text4.text,text5.text];
you will get your requirements...Dont forget to use resignFirstresponder to hide keyboard after u entered text...

How to send an email to a receipent in background in iOS5?

In an iPhone app,I want to send an email to a person who has forgotten about their passcode . I want to send the mail in background (cant use MFMailComposeViewController for this) and also the app must not be pushed to background . Is there a way to achieve this?
The best way of doing this is using SKPSMTPMessage. You can download it from here: https://github.com/jetseven/skpsmtpmessage This is a very easy solution that I have used before for using "Forgot Password" solutions in iOS apps. To implement simply drag the downloaded files into your application, #import the the "SKPSMTPMessage.h" into your class, and implement the following code:
.h
#import "SKPSMTPMessage.h"
#interface SomeView : UIViewController <SKPSMTPMessageDelegate> {
}
- (IBAction)forgotPassword;
.m
- (IBAction)forgotPassword {
SKPSMTPMessage *forgotPassword = [[SKPSMTPMessage alloc] init];
[forgotPassword setFromEmail:#"some-email#gmail.com"]; // Change to your email address
[forgotPassword setToEmail:#"user-email#gmail.com"]; // Load this, or have user enter this
[forgotPassword setRelayHost:#"smtp.gmail.com"];
[theMessage setRequiresAuth:YES]; // GMail requires this
[forgotPassword setLogin:#"some-email#gmail.com"]; // Same as the "setFromEmail:" email
[forgotPassword setPass:#"password"]; // Password for the Gmail account that you are sending from
[forgotPassword setSubject:#"Forgot Password: My App"]; // Change this to change the subject of the email
[forgotPassword setWantsSecure:YES]; // Gmail Requires this
[forgotPassword setDelegate:self]; // Required
NSString *newpassword = #"helloworld";
NSString *message = [NSString stringWithFormat:#"Your password has been successfully reset. Your new password: %#", newpassword];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain", kSKPSMTPPartContentTypeKey, message, kSKPSMTPPartMessageKey, #"8bit" , kSKPSMTPPartContentTransferEncodingKey, nil];
[forgotPassword setParts:[NSArray arrayWithObjects:plainPart, nil]];
[forgotPassword send];
}
Also be sure to include the following methods in the .m. You can change the contents of the UIAlertViews depending on what you want to display to the user.
- (void)messageSent:(SKPSMTPMessage *)message {
NSLog(#"Message Sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Password Reset" message:#"Check your email for your new password." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error {
NSLog(#"Message Failed With Error(s): %#", [error description]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was an error reseting your password. Please try again later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
You also need to do the following before this will work.
Your Target -> Get Info -> Build -> All Configurations -> Other Link Flags: "-ObjC"
If you need help with this, see http://developer.apple.com/qa/qa2006/qa1490.html
EDIT:
* CFNetwork.framework must also be added for this to work! *
Let me know if you have any more questions.
Thanks,
Jacob
You can't use MFMailComposeViewController to do this. No API will allow you to send emails or any kind of message on behalf of the user without he seeing it.
The only I see is to make a call to your server and the server send the email, something like this:
NSURLRequest requestWithURL:[NSURL urlWithString:#"http://server.com/send_passcode?to=email#lala.com"]];
You cannot send SMS/Email without user acceptance. But there are a lot of web-services in internet which can send SMS/Email. I guess some app uses those services or uses own.
You CAN send email in the background (without using the default MFMail Controller). BUT you still need the user to fill out whatever form (or content you want to email) and have them click "Send".
Here is my post on how to do it. It includes code and images.
Locking the Fields in MFMailComposeViewController
P.S. this works and Apple has approved over 10 of my apps that use this code/method.
In reference to the PostageApp comment below if you wanted to send emails without any hassle of setting up an SMTP client you can check out the PostageKit wrapper for using the PostageApp service. Let's you send emails with a couple lines of code reliably.
https://github.com/twg/PostageKit
May be you should implement PHP script that will send out email to user. In ios, you can use POST method in NSURLConnection to call PHP script. You can find many scripts on Google to send out email to user.
Download SKPSMTP Library and import
#import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h"
-(IBAction)btnRecoverClicked:(id)Sender;
Then implement the method for sending mail in background.
-(IBAction) btnRecoverClicked:(id)sender {
NSString *str=#"Your password is:";
NSString *strUserPassword=[NSString stringWithFormat:#"%# %#",str,struserPassword];
NSLog(#"Start Sending");
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail = #"XXXXX"; //sender email address
emailMessage.toEmail = struserEmail; //receiver email address
emailMessage.relayHost = #"smtp.gmail.com";
//emailMessage.ccEmail =#"your cc address";
//emailMessage.bccEmail =#"your bcc address";
emailMessage.requiresAuth = YES;
emailMessage.login = #"xxxxxxxx"; //sender email address
emailMessage.pass = #"XXXXXXX"; //sender email password
emailMessage.subject =#"Password Recovery";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
NSString *messageBody = [NSString stringWithFormat:#"Your password is: %#",struserPassword]
;
//for example : NSString *messageBody = [NSString stringWithFormat:#"Tour Name: %#\nName: %#\nEmail: %#\nContact No: %#\nAddress: %#\nNote: %#",selectedTour,nameField.text,emailField.text,foneField.text,addField.text,txtView.text];
// Now creating plain text email message
NSDictionary *plainMsg = [NSDictionary
dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
messageBody,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,nil];
//in addition : Logic for attaching file with email message.
/*
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"JPG"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *fileMsg = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx-
unix-mode=0644;\r\n\tname=\"filename.JPG\"",kSKPSMTPPartContentTypeKey,#"attachment;\r\n\tfilename=\"filename.JPG\"",kSKPSMTPPartContentDispositionKey,[fileData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,fileMsg,nil]; //including plain msg and attached file msg
*/
[emailMessage send];
// sending email- will take little time to send so its better to use indicator with message showing sending...
}
To handle the success and fail use
-(void)messageSent:(SKPSMTPMessage *)message{
NSLog(#"delegate - message sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message sent to your mail." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
and
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
https://github.com/troyz/MailUtil
I have used library above to send mail in background, so it works.
pod "MailUtil", :git => 'https://github.com/troyz/MailUtil.git', :tag => '0.1.0'
Swift code is here:
import MailUtil
SendEmailOperation.setupConfig(withServer: "smtp.foo.com", withFrom: "foo#mailserver.com", withLogin: "foo#mailserver.com", withPassword: "*********")
let operation = SendEmailOperation(to: "foo#mailserver.com", subject: "Hello", body: "world", path: "/selected/path/for/your/file.pdf")
operation?.completionBlock = {
debugPrint("Mail sent!")
DispatchQueue.main.async {
//showMailSentPopup()
}
}
do {
try SendEmailOperation.sendEmail(operation)
} catch {
debugPrint("Mail could not sent or sending result could not handle - \(error)")
}

problem with logging in twitter through my iphone application

i am creating a music application in which i am integrating twitter in my application
When a user clicks on particular song and then he click on the twitter tab the login page of twitter should be displayed. after entering the username and password he should be directed to the page where he can enter his comment and then post it.the problem is that when i click on twitter tab the login page is diplayed but when i enter he username and password and click on submit it does not redirect me to the page where i can post my comment. Here is my code:
(IBAction) Submit: (id) sender
{
// g=text3.text.integerValue;
u=text1.text;
p=text2.text;
int flag;
NSLog(#"Username,%d",u);
//if((u!=#"") || (p!=#""))
//if((text1.text.length >= 20 && range.length !=0) ||(text2.text.length >= 8 && range.length!=0))
if([text1.text length] != 0 || [text2.text length]!=0)
{
TwitterRequest * t = [[TwitterRequest alloc] init];
t.username =[NSString stringWithFormat: #"%#",u];
//NSString *username=[NSString stringWithFormat:#"%d",u];
t.password= [NSString stringWithFormat: #"%#",p];
//NSLog(#"Password,%d",p);
//#"ajeetyaday";
//t.username= #"ajeetyaday";
//t.password = #"gopalpur";
//NSString *name1 =[NSString stringWithFormat:#"%d",g]
//twitterMessageText.text=#" hi i am ajeet";
//[twitterMessageText resignFirstResponder];
loadingActionSheet = [[UIActionSheet alloc] initWithTitle:#"Posting To Twitter..." delegate:nil
cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
[loadingActionSheet showInView:self.view];
[t statuses_update:twitterMessageText.text delegate:self requestSelector:#selector(status_updateCallback:)];
//[TwitterRequest statuses_update:twitterMessageText.text delegate:self requestSelector:#selector(status_updateCallback:)];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Clicked on Submit" message:#"Please inter Username and Password" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
I think u r in wrong way!!
U simply store user name and password in a global variable,and push to posting page
(IBAction) Submit: (id) sender
{
user_name=uname.text;
password=password.text;
Twitter *Controller = [[Twitter alloc] init];
[self.navigationController pushViewController:Controller animated:YES];
[Controller release];
}

Attaching plain text file using MFMailComposer in iPhone SDK

I've been trying to use MFMailComposer to send a text file with encrypted data within. The problem is my attachment never shows up when when the email arrives in the inbox. Instead, a line of "<br/><br/>" is always present. I'm assuming is has something to do with the mime type and the receivers mail server not know how to read the data but I just can't figure out a solution.
Anyone come across this before and have a solution?
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
mailController.mailComposeDelegate =self;
[mailController setSubject:#"Records"];
[mailController setMessageBody:#"" isHTML:YES];
[mailController addAttachmentData:dataToBeEncrypted mimeType:#"text/plain" fileName:#"Records.txt"];
[self presentModalViewController:mailController animated:YES];
[mailController release];
} else {
//Pop up a notification
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Could not send email. Verify Internet conneciton and try again." delegate:nil cancelButtonTitle:#"Done" otherButtonTitles:nil];
[alert show];
[alert release];
}
Thanks for any help you can give!
Think I got a fix. I just took a shot in the dark after seeing another example and it seemed to work. For mimetype, I just put #"mime".
I'm a little weary of it, so I'll have to do some more testing to make sure the file always comes out correct.