Add saved email string to email recipient - ios

To save user time when emailing, user saves there email address in a preferences page that should pre fill the recipient when email is composed. (or thats what im trying to do) Here is where im stuck, how do I use my saved string to an object for the purpose of pre filling the recipient.
Currently the string does not pre fill the recipient
saves here in preferences page:
NSString *savecontents = _emailAddress.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savecontents forKey:#"saveEmail"];
[defaults synchronize];
Reads here in mail view presentation
- (IBAction)email:(id)sender {
NSString *savedValue = [[NSUserDefaults standardUserDefaults] <---------- saved email string
stringForKey:#"saveEmail"];
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
NSArray *toRecipients = [NSArray arrayWithObject:savedValue]; <------- trying to get string here
[mail setToRecipients:toRecipients];
[mail setSubject:#"subject"];
NSString *emailBody = [NSString stringWithFormat: #"text here"] ;
[mail setMessageBody:emailBody isHTML:YES];
mail.modalPresentationStyle = UIModalPresentationPageSheet;
[self presentModalViewController:mail animated:YES];
}
tried so far:
NSArray *toRecipients = [NSString stringWithFormat:savedValue];
[mail setToRecipients:toRecipients];
and
NSArray *toRecipients = [NSString stringWithFormat:#"%#",savedValue];
[mail setToRecipients:toRecipients];
and
Google, SO and banging fist on desk

All you need is this:
if (savedValue.length) {
[mail setToRecipients:#[ savedValue ]];
}
This uses modern Objective-C array syntax. This would be the same as:
if (savedValue.length) {
NSArray *toRecipients = [NSArray arrayWithObject:saveValue];
[mail setToRecipients:toRecipients];
}
The code you have you are trying to assign an NSString value to an NSArray variable.
Also, please don't use stringWithFormat unless you actually have a need to format a string.

Related

HTML in MFMailComposeViewController

I am a new in Xcode and i was working with mail app which uses MFMailComposeViewController. I wanted to design my *messageBody with HTML. Actually its a small "BOOK A MEETING" app. So I wanted to put date and time feild so that user could choose date and time. But when i run my app, i cannot enter anything in my date and time feild. Here is my code. Hope i could get some help.
- (IBAction)BookAMeeting:(id)sender {
//email subject
NSString *emailTitle = #"Haven Support";
//email content
NSMutableString *messageBody = [NSMutableString string];
[messageBody appendString:#"<h1>Please Enter the following feilds to book a meeting.</h1>\n"];
[messageBody appendString:#"<form>NAME: <input type = 'text' name='fname'> \n <br>TIME: <input type = 'time' name='timee'><br>\n DATE: <input type = 'date' name='date'><br>"];
//to address
NSArray *toRecipents = [NSArray arrayWithObject:#"xyz#hotmail.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc]init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:YES];
[mc setToRecipients:toRecipents];
//present mail view controller on screen
[self presentViewController:mc animated:YES completion:NULL];
}

Attaching a txt-file in mailcomposer ios 7

When use my following script, then the picture and the logfile would be a attached file. Also some other Text (the default signature) from the email would be attached as index.htm to the email when i open it with Outlook.
The Email is sent out from the iPad with iOS 7.0.6
In the Mail-Application on the Mac, the Files are in the middle of the text, before the signature of the mail-application would be written.
When i attach only the image, then all would be fine. When i attache also the logfile.txt, then its like I have descripted and in the Mail-Application of the mac, all special keys (german like ä, ü) are not decoded as utf8.
Where did I make the mistake?
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
currentIOS = [[UIDevice currentDevice] systemVersion];
vNumber = #"V"VersionNumber;
subject = [NSString stringWithFormat:#"%# - Meine aktuelle iPad-Nummer",vNumber];
message = [NSString stringWithFormat:#"<p>Hallo liebes EDV-Team,</p> <p>mein Betriebssystem ist: %#</p><p>Und meine iPad-Nummer lautet: %#</p>", currentIOS, udid];
[controller setToRecipients: [NSArray arrayWithObjects:#"email#webpage.de", nil]];
[controller setSubject:subject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *txtFilePath = [documentsDirectory stringByAppendingPathComponent:#"logfile.txt"];
NSData *noteData = [NSData dataWithContentsOfFile:txtFilePath];
[controller addAttachmentData:noteData mimeType:#"text/plain" fileName:#"logfile.txt"];
UIImage *roboPic = [UIImage imageNamed:#"world_smilie.png"];
NSData *imageData = UIImagePNGRepresentation(roboPic);
[controller addAttachmentData:imageData mimeType:#"image/png" fileName:#"smile.png"];
[controller setMessageBody:message isHTML:YES];
if ([self respondsToSelector:#selector(presentViewController:animated:completion:)]){
[self presentViewController:controller animated:YES completion:nil];
}
I changed the code for the textfile:
I change the code like elio.d told me:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *txtFilePath = [documentsDirectory stringByAppendingPathComponent:#"logfile.txt"];
NSString *txtFileContent = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:nil];
NSData *txtFileData = [txtFileContent dataUsingEncoding:NSUTF8StringEncoding];
[controller addAttachmentData:txtFileData
mimeType:#"text/plain"
fileName:#"logfile.txt"];
The logfile.txt would be attached but the signature from the ipad would be attached to the email in ATT00002.htm and now i got also a empty ATT00001.htm
I have the same problem when i change the type of the email (isHTML:NO)

Send HTML email with SKPSMTP iOS

I am trying to send an HTML email from my SKPSMTP code in iOS. Right now, I'm just sending plain text, but I'm trying to upgrade that a little. I've included that code below.
I can't find any documentation. How can I upload an HTML file and include that as it's body. Also, there's an image that's being loaded from the same directory as the HTML file, if that makes a difference in the answer. Thanks.
NSMutableString *emailBody = [NSMutableString stringWithFormat:#"Here's your code again, "];
[emailBody appendString:userCode];
SKPSMTPMessage *email = [[SKPSMTPMessage alloc] init];
email.fromEmail = #"me#gmail.com";
NSString *toEmail = [NSString stringWithFormat:#"%#", self.loginInput.text];
email.toEmail = toEmail;
email.relayHost = #"smtp.gmail.com";
email.requiresAuth = YES;
email.login = #"me#gmail.com";
email.pass = #"myPass";
email.subject = #"Your Validation Code";
email.wantsSecure = YES;
email.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
emailBody,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey, nil];
email.parts = [NSArray arrayWithObjects:plainPart, nil];
// Send it!
[email send];
So, here's the answer I came across, just so everyone else can get the benefit of me struggling through:
//Send them an e-mail
NSError* error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource: #"loginEmail" ofType: #"html"];
NSString *result = [NSString stringWithContentsOfFile: path encoding:
NSUTF8StringEncoding error: &error];
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"<!--INJECT CODE HERE -->"
options:0
error:&error];
NSString *emailBody = [regex stringByReplacingMatchesInString:result options:0 range:NSMakeRange(0, [result length]) withTemplate:code];
NSLog(#"%#", [emailBody class]);
SKPSMTPMessage *email = [[SKPSMTPMessage alloc] init];
email.fromEmail = #"myemail#gmail.com";
NSString *toEmail = [NSString stringWithFormat:#"%#", self.loginInput.text];
email.toEmail = toEmail;
email.relayHost = #"smtp.gmail.com";
email.requiresAuth = YES;
email.login = #"myemail#gmail.com";
email.pass = #"myPass"
email.subject = #"Your Validation Code";
email.wantsSecure = YES;
email.delegate = self;
NSDictionary *htmlPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/html",kSKPSMTPPartContentTypeKey, emailBody,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey, nil];
email.parts = [NSArray arrayWithObjects:htmlPart, nil];
// Send it!
NSLog(#"ABOUT TO SEND");
[email send];
So, I had to write an HTML file, host all my images on tinypic to include in the HTML, write some text to regex switch out my code variable, load in it in here and attach it as the part of my email with key "text/html". This code works, but if anyone has any other suggestions that are helpful, I'm willing to mark them as the right answer!

Email attachment sent using SKPSMTPMessage appears in iOS mail client as contact

I have tested the code for sending attachments using this useful library:
Skpsmtpmessage library
The email seems to get sent correctly, and when I view it through hotmail or gmail clients I see the jpeg image. However, when I view this same email through an iOS mail client, the attachment appears as a "contact" and clicking on this gives me the option to save the file as a new contact.
I have tried sending an email with jpeg attachment from hotmail, and when I do this it appears correctly in the iOS client.
Does anyone know whether this is the code or iOS getting it wrong?
//the guts of the message.
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = #"aname#gmail.com";
testMsg.toEmail = #"aname#gmail.com";
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"aname#gmail.com";
testMsg.pass = #"password";
testMsg.subject = #"The message subject";
testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!
// Only do this for self-signed certs!
// testMsg.validateSSLChain = NO;
testMsg.delegate = self;
//email contents
NSDate* now = [NSDate date];
NSString * bodyMessage = [NSString stringWithFormat:#"The message body"];
// email image if it exists
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/file.jpeg"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableArray* parts = [[NSMutableArray alloc] init];
// add plain part
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
bodyMessage ,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
[parts addObject: plainPart];
// add attachments
NSData *attachmentData = [NSData dataWithContentsOfFile:jpgPath];
NSString *directory = #"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"file.jpeg\"";
NSString *attachment = #"attachment;\r\n\tfilename=\"file.jpeg\"";
NSDictionary *image_part = [NSDictionary dictionaryWithObjectsAndKeys:
directory,kSKPSMTPPartContentTypeKey,
attachment,kSKPSMTPPartContentDispositionKey,
[attachmentData encodeBase64ForData],kSKPSMTPPartMessageKey,
#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
[parts addObject: image_part];
testMsg.parts = parts;
[testMsg send];
Try to change
NSString *directory = #"text/directory;...
to
NSString *directory = #"text/jpeg;...
I hope this works for you!
Steffen

Launching MFMailComposeViewController cuts off recipient text

I am using Apple's sample code for the MessageUI and MFMailComposeViewControllerDelegate, and mostly it works great. But for some reason when I implement it, the text in the recipient fields appears out of alignment with the field labels, and you can only see half of the cursor and half of the text while typing. Once you've typed the addresses and exited the field, the text is completely visible, though still out of alignment with the labels. I have looked at other apps' implementations of the MessageUI, and they do not seem to have this problem. has anyone seen this problem and found a solution?
Below is code:
-(void)displayComposerSheet
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Data"];
// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:#"email#example.com"];
[picker setToRecipients:toRecipients];
// Attach an attachment to the email
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *csvFile = [documentsDirectory stringByAppendingPathComponent:#"myFile.csv"];
NSData *myData = [NSData dataWithContentsOfFile:csvFile];
NSString *filename = #"myFile.csv";
[picker addAttachmentData:myData mimeType:#"text/csv" fileName:filename];
// Fill out the email body text
NSString *emailBody = #"Attached is the data";
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
}
The problem occurs in both the simulator and on device.
Probably, you've got a custom UITextField in your app and have some custom code in - (CGRect)textRectForBounds:(CGRect)bounds. If you'd like to have some category for UITextField class, try to put your specific code directly to the class where you using that instead of using category, which affects all textfields in your app, even in MFMailComposeViewController

Resources