I want to send automatically an email to sender (hard coded email id) from iphone on particular timeInterval. How i send an email automatically without using UI of MFMailComposeViewController class?
Thanks.
There is nothing in the built in frameworks that will allow it. You could of course use the unix sockets api to conect to a mail server and send a message using SMTP, however there are some third party ibraries to make your life easier.
I have used the Pantomine messaging library. It works well on iOS and can be found at http://www.collaboration-world.com/pantomime/
Once you have the library in your project you can do something like this:
CWMessage *message = [[CWMessage alloc] init];
CWInternetAddress *from = [[CWInternetAddress alloc] initWithString:#"from#gmail.com"];
[message setFrom:from];
[from release];
CWInternetAddress *to = [[CWInternetAddress alloc] initWithString:#"to#somewhere.com"];
[address setType:PantomimeToRecipient];
[message addRecipient:to];
[to release];
[message setSubject:#"This is my subject"];
[message setContentType: #"text/plain"];
[message setContentTransferEncoding: PantomimeEncodingNone];
[message setCharset: #"us-ascii"];
[message setContent: [#"This is my message" dataUsingEncoding: NSASCIIStringEncoding]];
smtp = [[CWSMTP alloc] initWithName:#"smtp.gmail.com" port:465];
[smtp setDelegate: self];
[smtp setMessage: message];
[message release];
ssl = YES;
mechanism = #"PLAIN";
[smtp connectInBackgroundAndNotify];
Related
I am developing an IOS Chat application using XMPP Protocol(ejabberd). My chat room is created at my server, it return roomID to me.
I am facing an issue in room/group chat. When i am sending a single message it is repeating more than once like 3 to 4 times.How to fix this. My code is here
XMPPJID *roomJID = [XMPPJID jidWithString:[roomDict objectForKey:KEY_group_id]];
XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:xmppRoomCoreDataStorage jid:roomJID dispatchQueue:dispatch_get_main_queue()];
[xmppRoom activate:[ChatHandler sharedInstance].xmppStream];
[xmppRoom addDelegate:self
delegateQueue:dispatch_get_main_queue()];
[self insertRoomObjectWithDictionary:roomDict];
[xmppRoom joinRoomUsingNickname:[[ChatHandler sharedInstance] xmppStream].myJID.user
history:nil
password:#""];
[xmppRoom fetchConfigurationForm];
return xmppRoom;
Following code snippet worked for me.. Try it for your code...
I have sent uuid of my device as child while sending message and checked the same uuid at the time of incoming message :
-(void)sendMessageWithBody:(NSString *)messageBody
{
if ([messageBody length] == 0) return;
NSXMLElement *body = [NSXMLElement elementWithName:#"body" stringValue:messageBody];
XMPPMessage *message = [XMPPMessage message];
[message addChild:body];
NSString *uuidString=[UIDevice currentDevice].identifierForVendor.UUIDString;
NSXMLElement *myMsgLogic=[NSXMLElement elementWithName:#"myMsgLogic" stringValue:uuidString];
[message addChild:myMsgLogic];
[self sendMessage:message];
}
-(void)xmppRoom:(XMPPRoom *)sender didReceiveMessage:(XMPPMessage *)message fromOccupant:(XMPPJID *)occupantJID;
{
[self handleIncomingMessage:message room:xmppRoom];
}
-(void)handleIncomingMessage:(XMPPMessage *)message room:(XMPPRoom *)room
{
NSString *uuidString=[UIDevice currentDevice].identifierForVendor.UUIDString;
NSString *messageLogic= [[message elementsForName:#"myMsgLogic"].firstObject stringValue];
if ([uuidString isEqualToString:messageLogic]) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"handleIncomingMessage" message:[message body] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
I have the same chat application using xmpp ejabbered. I was also facing the same problem. In my case on xmpp server they have set offline message storage to 100. If in offline mode the message limit crossed 100 then from 101th message I will get bounce back that message. So as a solution we changed the offline message limit to 500.
{mod_offline_odbc, [
{user_max_messages, 500}
]}
I am making an application where I want to send an email using smtp server.
It's working fine but if user does not provide the correct gmail account details such as (email id and password) email is not send.
What I want to do is I want to access user gmail account details from setting tab of the iPhone into my app?
Is it possible to do retrieve the gmail account detail into the app?
Please help me out with this.
Following is my code:
-(IBAction)sendemail
{
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
//testMsg.fromEmail = #"Lexi mobile";//nimit51parekh#gmail.com
testMsg.fromEmail = soundOn;
NSLog(#"str_Uname=%#",testMsg.fromEmail);
//str_info = [str_info stringByReplacingOccurrencesOfString:#"," withString:#""];
testMsg.toEmail = [string_emailinfo objectAtIndex:0];
NSLog(#"autoemail=%#",testMsg.toEmail);
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = soundOn;
NSLog(#"autoelogin=%#",testMsg.login);
testMsg.pass = vibrateOn;
NSLog(#"autopass=%#",testMsg.pass);
testMsg.subject = #"Photo Sharing";
testMsg.wantsSecure = YES;
NSURL *url = [[NSURL alloc]initWithString:#"http://itunes.apple.com/us/app/umix-radio/id467041430?mt=8"];
NSString *msg2 = [NSString stringWithFormat:#"<html><b>DOWNLOAD NOW</b>  </html>",url];
NSString *sendmsg=[[NSString alloc]initWithFormat:#"%#",msg2];
NSLog(#"automsg=%#",sendmsg);
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
sendmsg,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
// [self DeleteRowAfterSending];
//[self performSelector:#selector(DeleteRowAfterSending) withObject:nil afterDelay:5.0];
}
-(void)messageSent:(SKPSMTPMessage *)message
{
[message release];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success" message:#"Your email is sent successfully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert 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:#"Fail" message:#"Message sending failure" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
What i want to do is i want to access user gamil account details from
setting tab of the iPhone into my app? is it possible to do retrive
the gamil account detail into the app?
No, and with good reason: that functionality would allow any developer access to anyone's e-mail account.
That would be a massive security hole.
Much like it is with Location Services, you're just going to have to ask the user to enter their e-mail address and password. And hope they want to trust your app with that kind of personal information. (Assuming Apple approves your app at all.)
Let the user give your app authorization from Google. check the oauth autorization with google api at their developers site?
https://developers.google.com/accounts/docs/OAuth2
As usual the user signs in with his account through google api and returns back to you an access_token to get information back from his account including his email which you need.
How can I add video/image/audio as an attachment programmatically in the email in iPhone app iPhone and how can I add Signature? I think it can be done by using html tags but how it can be done. Can you please any sample code for this.
Thanks-
To send attachments: You can use MFMailComposeViewController to send attachments from your app.
1. Add MessageUI framework, and do #import <MessageUI/MFMailComposeViewController.h>
2. In your email button action or however you are sending email, add :
if([MFMailComposeViewController canSendMail]) //IMPORTANT: check if mail can be sent to avoid crash
{
MFMailComposeViewController*mailController=[[MFMailComposeViewController alloc] init];
NSURL*yourUrl=[NSURL fileURLWithPath:yourFilePath];
NSData*attachData=[NSData dataWithContentsOfURL:yourUrl];
mailController.mailComposeDelegate=self;
[mailController addAttachmentData:attachData mimeType:#"yourExtension" fileName:#"yourFileName.yourExtension"];
[mailController setSubject:#"Test Subject"];
[mailController setTitle:#"Test Title"];
if(mailController!=nil)
{
[self presentModalViewController:mailController animated:YES];
}
[mailController release];
}
else //give a prompt showing no mail accounts found
{
UIAlertView*emailAlert=[[UIAlertView alloc] initWithTitle:#"No Email Account Found." message:#"Please set an email account." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[emailAlert show];
[emailAlert release];
}
To set signature: I guess it uses the signature relative to the mail account that has been set. Sorry no idea on how to change it programmatically.
I want to send mail from my custom iPhone app. I have used MFMailComposeViewController to send mail from my iphone in my previous app. Now, i don't want to show the MFMailComposeViewController to the user, if they click Send Mail button the mail automatically send to the recipient mail address. How can i do this? Can you please help me on this? Thanks in advance.
I have used below code to show the MFMailComposeViewController,
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"Details"];
[controller setMessageBody:#"Hi" isHTML:NO];
[controller setToRecipients:[NSArray arrayWithObjects:#"abcd.m#gmail.com", nil]];
[self presentModalViewController:controller animated:YES];
[controller release];
Sending emails programmatically, without user intervention, from an iphone application, cannot be implemented using any of the Apple frameworks. It could be possible in a jailbroken phone but then it would never see the inside of App Store.
If you want control of email sending, then a better way would be to set up a web service (at your server end) you can post to using an HTTP request. If you are posting to only one address this can work very well, although you may want to get the user to input their return mail address.
Otherwise only the standard dialog is available (this relies on using whatever account they've setup on the device).
The iOS SDK has made it really easy to send email using the built-in APIs. With a few line of codes, you can launch the same email interface as the stock Mail app that lets you compose an email. You can pop up mail composer form , write message and can send plain mail or file attached mail using MFMailComposeViewController class. For more info : Sending e-mail from your iOS App
But, in this section what i am going to explain is about sending emails without showing the mail composer sheet ie. sending emails in background. For this feature, we can not use iOS native MFMailComposer class because it does not allow us to send emails in background instead it pop ups the mail composer view from where user have to tap "send" button , so for this section i am going to use SKPSMTPMessage Library to send emails in background, however email account has to be hardcoded on this method.
Limitations :
sender/receiver email address has to be hardcoded or you have to grab it using some pop up form in your app where user inputs sender/receiver email address. In addition, sender account credentials has to be also hardcoded since there is no way we can grab it from device settings.
Method :
Import CFNetwork.framework to your project.
Include #import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h" // for Base64 encoding
Include to your ViewController
Download SKPSMTPMessage library from
https://github.com/jetseven/skpsmtpmessage
Drag and Drop "SMTPLibrary" folder you have downloaded to your project.
Before proceeding, let you know that i am using sender/receiver email address and sender password hardcoded in the code for this example.But, you may grab this credentials from user, allowing them to input in some sort of forms(using UIViews).
-(void) sendEmailInBackground {
NSLog(#"Start Sending");
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail = #"sender#gmail.com"; //sender email address
emailMessage.toEmail = #"receiver#gmail.com"; //receiver email address
emailMessage.relayHost = #"smtp.gmail.com";
//emailMessage.ccEmail =#"your cc address";
//emailMessage.bccEmail =#"your bcc address";
emailMessage.requiresAuth = YES;
emailMessage.login = #"sender#gmail.com"; //sender email address
emailMessage.pass = #"Passwxxxx"; //sender email password
emailMessage.subject =#"#"email subject header message";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
NSString *messageBody = #"your email body message";
//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...
}
Now, handling delegate methods :
// On success
-(void)messageSent:(SKPSMTPMessage *)message{
NSLog(#"delegate - message sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message sent." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
// On Failure
-(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]);
}
Ok, thats all from the coding side. hope this tutorial may find useful for you guyz
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)")
}