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.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In my iphone application, in MFMailComposer, I m adding an attachment. that attachment as a url link.in that link there is a pdf file. When I click send the url link is not sent to destination mail address.
I am using this code
-(void)sendMail
{
MFMailComposeViewController *mailView= [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate=self;
[mailView setSubject:titleString];
NSArray *array = [[NSArray alloc]initWithObjects:emailString, nil];
[mailView setToRecipients:array];
NSData *textData = [NSData dataWithContentsOfFile:self.fileString];
[mailView addAttachmentData:textData mimeType:#"text/plain" fileName:self.fileString];
[mailView setMessageBody:self.templatetextstring isHTML:YES];
[self presentModalViewController:mailView animated:YES];
}
Use this code
NSString *link = [NSString stringWithFormat:#"http://www.google.com"];
[controller setMessageBody:[NSString stringWithFormat:#"<p><font size=\"2\" face=\"Helvetica\"><a href=%#></br>%#</br></a></br></font></p>",link,#"Google"] isHTML:YES];
Hope it helps you..
I am not sure I understand your question probably whether you want to attach a pdf document or whether you just want to add a link to a pdf document so I will answer both. Here is the code I use to attach pdf data onto an email
- (void)emailFile
{
if(![MFMailComposeViewController canSendMail]) {
UIAlertView *cantSend = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Device not configured to send email" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[cantSend show];
} else {
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[mailView setSubject:#"PDF Attached to email"];
// Adding an actual PDF document to the email.
[mailView addAttachmentData:(__bridge NSData *)myPDFData mimeType:#"pdf" fileName:#"AttachedPDFDocument"];
[mailView setMessageBody:[NSString stringWithFormat:#"Sending %#. This email maybe sent as junk mail",fileName] isHTML:NO];
[self presentModalViewController:mailView animated:YES];
}
}
Notice I am adding the pdf data and not the actual pdf and then I set the extension (MimeType) to pdf and then set the name of the file it is that simple to add an attachment onto an email you are constructing.
To add a link to an email it is as simple as
- (void)emailFile
{
if(![MFMailComposeViewController canSendMail]) {
UIAlertView *cantSend = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Device not configured to send email" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[cantSend show];
} else {
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;
[mailView setSubject:#"PDF Link added in HTML"];
// Adding a HTML Link to an email. Remembering to set the Message to allow HTML.
NSString *link = [NSString stringWithFormat:#"http://www.google.com"];
[mailView setMessageBody:[NSString stringWithFormat:#"<p><font size=\"2\" face=\"Helvetica\"><a href=%#></br>%#</br></a></br></font></p>",link,#"Google"] isHTML:YES];
[self presentModalViewController:mailView animated:YES];
}
}
Notice that you aren't attaching any data put you are setting the setMessage to use HTML whereas the first example doesn't use HTML. This will now allow you to set an NSString in the message body that contains html elements.
EDIT
myPDFData is a CFDataRef of the dataContent of the PDF that I download from a webservice then the user can forward it to themselves via an email. If you are using ARC then you will need to add the bridge in (__bridge NSData *)myPDFData when setting attachmentData.
Hope this helps.
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
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)")
}