How to send a label's text as an email attachment? - iphone

I want to attach a label text to an email,
How can I send a text inside a UILabel as an attachment to email ?
This is the code I'm using :
-(IBAction)send:(id)sender {
if ([MFMailComposeViewController canSendMail])
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 100)];
label.numberOfLines = 0;
label.textAlignment = UITextAlignmentCenter;
label.text = #"text";
[self.view addSubview:label];
[label release];
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"Subject"];
NSString *fileName = #"my file.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [NSData dataWithContentsOfFile:path];
[mailer addAttachmentData:myData mimeType:#"text/plain" fileName:fileName];
// Fill out the email body text
NSString *emailBody = #"Email Body";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
[mailer release];
}
else
{
UIAlertView *alertm = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Please make sure that your email application is open"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertm show];
[alertm release];
}
}
How can I link that label to attach it to email ?
Any help will be appreciated.

you're almost there.
-- you read text from a file and attach it
===
read the data not from the file but from the label itself
NSData *data = [self.label.text dataUsingEncoding:NSUTF8Encoding];

You can add the Label text to the Body.
NSString *emailBody = [NSString stringWithFormat:#"Your Voice File Attached. %#", label.text];
something like this

Related

how to attach any document in email in iphone app

I am sending email from iphone app it is working fine but i want that with email i should attached a pdf file which is documents folder of the app.for testing first i attached a png from resources folder of app but it does not get attached and not sent in email i am using following code.
- (IBAction)onEmailResult
{
if ([[MFMailComposeViewController class] canSendMail]) {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Pig Game"];
[picker setToRecipients:toRecipients];
int a=10;
int b=100;
NSString *path = [[NSBundle mainBundle] pathForResource:#"project existing photo" ofType:#"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"png" fileName:#"icon.png"];
NSString * emailBody = [NSString stringWithFormat:#"My Score %d",a];
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];
}
else {
int a=10;
int b=20;
NSString *recipients = #"mailto:imran_husain_2000#yahoo.com?&subject=Pig Game";
NSString *body = [NSString stringWithFormat:#"&body=My Score: %d/%d, My Time: %#", a,b, time];
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
}
Try following code snippet.
- (NSString *)pathForFile : (NSString *) fileName{
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: fileName];
}
- (void)sendMailWithAttachedFile:(NSString *) fileName extention:(NSString *) extension{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForResourse:fileName ofType:extension]];
NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForFile:[NSString stringWithFormat:#"%#.%#", fileName, extension]]];
NSData *data=[[NSData alloc]initWithContentsOfURL:outputURL];
[picker addAttachmentData:data mimeType:#"application/pdf" fileName:#"TestOne.pdf"];
[self presentViewController:picker animated:YES completion:nil];
}
Now Call Send Mail method As:
[self sendMailWithAttachedFile:#"TestOne" :#"pdf"];
-(void)displayMailComposerSheet
{
NSData *soundFile = [[NSData alloc] initWithContentsOfURL:YourDocumentFile];
[mail addAttachmentData:soundFile mimeType:#".txt" fileName:#"YourDocumentFile.txt"];
}
This code implement in displayMailComposerSheet i hope this code is useful for You
MFMailComposeViewController *picker1 = [[MFMailComposeViewController alloc] init];
NSArray *recipentsArray = [[NSArray alloc]initWithObjects:[shopDictValues objectForKey:#"vEmail"], nil];
picker1.mailComposeDelegate = self;
picker1.modalPresentationStyle = UIModalPresentationFormSheet;
[picker1 setSubject:#"Subject"];
[picker1 setToRecipients:recipentsArray];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableArray *arydefault = [[NSMutableArray alloc]initWithArray:[[NSUserDefaults standardUserDefaults] valueForKey:#"jacketCount"]];
for (int i=0;i<arydefault.count;i++)
{
NSString *pdfFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#%#.pdf",[[arydefault objectAtIndex:i]valueForKey:#"productlinename"],[arydefault objectAtIndex:i]]];
[picker1 addAttachmentData:[NSData dataWithContentsOfFile:pdfFilePath] mimeType:#"application/pdf" fileName:[NSString stringWithFormat:#"Order - %#",[[[NSString stringWithFormat:#"%#%i",[[arr objectAtIndex:i]valueForKey:#"productlinename"],i] componentsSeparatedByCharactersInSet: [[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:#""]]];
}
NSString *emailBody = #"Email Body goes here.";
[picker1 setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:picker1 animated:YES];

Attaching a mp3 file to email directly from app?

I am working on an app where, if the user selects a sound, they can email it to themselves from the app.
The attachment part 'appears' to work, however, when I send the email, the recipient has no attachment?
On the iPad/iPhone itself, it looks like it is attaching it when it comes to compose, but it is not working? :/
Here is the code I am using;
- (void)onSend:(id)sender{
int nIndex;
UIButton *btnSender = (UIButton *)sender;
NSLog( #"%d", btnSender.tag );
for ( int i = 0; i < [ m_aryFileName count ]; i++ ) {
if( i == ( btnSender.tag - 100 ) ){
nIndex = i;
}
}
NSString *strFileName = [ m_aryFileName objectAtIndex:nIndex ];
strFileName = [ strFileName stringByAppendingString:#".mp3" ];
NSData* nData = [ NSData dataWithContentsOfFile:strFileName ];
MFMailComposeViewController *pickerMail = [[MFMailComposeViewController alloc] init];
pickerMail.mailComposeDelegate = self;
[pickerMail setSubject:#"myMail Attachment"];
// Attach an image to the email
[pickerMail addAttachmentData:nData mimeType:#"audio/mp3" fileName:strFileName ];
// Fill out the email body text
NSString *emailBody = #"Here is your attachment";
[pickerMail setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:pickerMail animated:YES];
[pickerMail release];
}
try this code mate,
NSString *strFileName = [m_aryFileName objectAtIndex:nIndex];
strFileName = [strFileName stringByAppendingString:#".mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:strFileName];
NSData *nData = [[NSData alloc] initWithContentsOfURL:fileURL];
MFMailComposeViewController *pickerMail = [[MFMailComposeViewController alloc] init];
pickerMail.mailComposeDelegate = self;
[pickerMail setSubject:#"myMail Attachment"];
[pickerMail addAttachmentData:nData mimeType:#"audio/mpeg" fileName:strFileName ];
NSString *emailBody = #"Here is your attachment";
[pickerMail setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:pickerMail animated:YES];
Below code might be useful to you:
NSData *videoData = [NSData dataWithContentsOfURL:mediaUrl];
[mailcomposer addAttachmentData:videoData mimeType:#"video/mp4" fileName:#"Video"]
Try using a mime type of audio/mpeg instead. You can get this value by running the following code:
#import <MobileCoreServices/MobileCoreServices.h>
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,
(__bridge CFStringRef)#"mp3",
NULL);
CFStringRef mimeTags = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType);
CFRelease(uti);
NSString *mediaType = [NSString stringWithString:(__bridge NSString *)mimeTags];
CFRelease(mimeTags);
How does that work?
if ([MFMailComposeViewController canSendMail] && m_pDataArray != nil)
{
NSString * pSongPath = [[NSBundle mainBundle] pathForResource:#"song" ofType"#"mp3"]; ;//get the file
MFMailComposeViewController * pMailComposer = [[MFMailComposeViewController alloc] init];
pMailComposer.mailComposeDelegate = self;
[pMailComposer setMessageBody:#"msg body" isHTML:NO];
NSURL * pFileUrl = [[[NSURL alloc] initFileURLWithPath:pSongPath] autorelease];
NSData * pData = [[[NSData alloc] initWithContentsOfURL:pFileUrl] autorelease];
[pMailComposer addAttachmentData:pData mimeType:#"audio/mpeg" fileName:#"song.mp3" ]];
[self presentModalViewController:pMailComposer animated:YES];
[pMailComposer release];
}
else
{
UIAlertView *pAlert = [[UIAlertView alloc] initWithTitle:#"Failure" message:#"Your device doesn't support the composer sheet" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[pAlert show];
[pAlert release];
pAlert = nil;
}
be sure that the file should have valid extension like .mp3 , in that case it will work properly

How to Send image in Email body?

I am sending image with some text in Email Body using this link my code is given below
NSString *urlString = #"url";
NSString *searchingurl = [NSString stringWithFormat:#"%#%#", urlString,idnumber];
NSString *string = [NSString stringWithFormat:#"%#<br><br>Item No :%#<br>Type :%#<br>Size : %#",searchingurl,str123,mytype,itemsize];
NSMutableString *emailBody = [[[NSMutableString alloc] initWithString:#"<html><body>"] retain];
NSData *imageData = UIImageJPEGRepresentation(myImage, 1.0f);
NSString *encodedString = [imageData base64Encoding];
[emailBody appendString:[NSString stringWithFormat:#"<p><b><img src='data:image/png;base64,%#'></b></p>",encodedString]];
[emailBody appendString:string];
[emailBody appendString:#"</body></html>"];
NSLog(#"%#",emailBody);
MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
emailDialog.mailComposeDelegate = self;
[emailDialog setSubject:#""];
[emailDialog setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:emailDialog animated:YES];
[emailDialog release];
[emailBody release];
Screenshow for above code
After Sending Mail to Yahoo it show my image and text on both Mackbook and in iphone device , when i send mail to Gmail and checked it in iphone device it show image with text but When i checked gmail in Mackbook it not show my image
Some one Can guide me why my image not show in Gmail on PC.Any help will be appriated.Thanks
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Your subject"];
// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:#""];
//NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
//NSArray *bccRecipients = [NSArray arrayWithObject:#"fourth#example.com"];
[picker setToRecipients:toRecipients];
//[picker setCcRecipients:ccRecipients];
//[picker setBccRecipients:bccRecipients];
NSLog(#"Video size >> %d",(videodta.length/1024)/1024);
[picker addAttachmentData:imageData mimeType:#"image/png" fileName:#"testapp"];
// Fill out the email body text
NSString *emailBody = #"Type your message here";
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
}

Data Attached in E-mail?

My NSMutableArray data are in NSData formate.I am trying to attached NSMutableArray data to E-mail body.Here is my NSMutableArray code:
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSString *msg1 = [defaults1 objectForKey:#"key5"];
NSData *colorData = [defaults1 objectForKey:#"key6"];
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
NSData *colorData1 = [defaults1 objectForKey:#"key7"];
UIColor *color1 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData1];
NSData *colorData2 = [defaults1 objectForKey:#"key8"];
UIFont *color2 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData2];
CGFloat x =(arc4random()%100)+100;
CGFloat y =(arc4random()%100)+250;
lbl = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 100, 70)];
lbl.userInteractionEnabled=YES;
lbl.text=msg1;
lbl.backgroundColor=color;
lbl.textColor=color1;
lbl.font =color2;
lbl.lineBreakMode = UILineBreakModeWordWrap;
lbl.numberOfLines = 50;
[self.view addSubview:lbl];
[viewArray addObject:lbl ];
viewArray is my NSMutableArray .All the data store in viewArray are in NSData formate.I try this code to attached viewArray data in E-mail.
- (IBAction)sendEmail {
if ([MFMailComposeViewController canSendMail])
{
NSArray *recipients = [NSArray arrayWithObject:#"example#yahoo.com"];
MFMailComposeViewController *controller = [[MFMailComposeViewController
alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"Iphone Game"];
NSLog(#"viewArray: %#", viewArray);
NSString *string = [viewArray componentsJoinedByString:#"\n"];
NSString *emailBody = string;
NSLog(#"test=%#",emailBody);
[controller setMessageBody:emailBody isHTML:YES];
[controller setToRecipients:recipients];
[self presentModalViewController:controller animated:YES];
[controller release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Your device is not set up for email." delegate:self
cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
Here i see objects store in viewArray.in console its look like this..[2012-05-07 18:48:00.065 Note List[279:207] test=UILabel: 0x8250850; frame = (140 341; 56 19); text = 'Xxxxxxx'; clipsToBounds = YES; layer = > but in E-mail i see only this..>> please suggest any one how can i attached my viewArray data in E-mail.
]
in email attachement, you can only send NSData or string to email, now if you want to send it by string, then get all values you want to send email like, lable.text, lable.color, lable.alpha etc, with proper keys and place it in the body and parse there, else find some way to convert your object into NSData and attach it using mfmailcomposer attach data method
read this to convert NSArray into NSData
How to convert NSArray to NSData?
and this to convert back the NSData to NSArray
How can i convert a NSData to NSArray?
and then write this data to file as,
-(void)writeDataToFile:(NSString*)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if(filename==nil)
{
DLog(#"FILE NAME IS NIL");
return;
}
// the path to write file
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"%#",filename]];
/*NSData *writeData;
writeData=[NSKeyedArchiver archivedDataWithRootObject:pArray]; */
NSFileManager *fm=[NSFileManager defaultManager];
if(!filePath)
{
//DLog(#"File %# doesn't exist, so we create it", filePath);
[fm createFileAtPath:filePath contents:self.mRespData attributes:nil];
}
else
{
//DLog(#"file exists");
[self.mRespData writeToFile:filePath atomically:YES];
}
NSMutableData *resData = [[NSMutableData alloc] init];
self.mRespData=resData;
[resData release];
}
and finally attach it to the email using
- (void)addAttachmentData:(NSData *)attachment mimeType:(NSString *)mimeType fileName:(NSString *)filename

Find Photo in Directory! (Programmatically)

Holy Dudes from stackoverflow,
MY PROBLEM: I need to send an email with 3 attachments. The first that is the .txt, is going well, no problems with him, but the problem is with the pictures. I capture a printscreen with this:
-(IBAction)screenShot{
maintimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(update) userInfo:nil repeats:YES];
}
-(void)update{
time = time + 1;
if(time == 2){
[self hideThem]; //hides the buttons
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(screenImage, nil, nil, nil);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"GRAPH SAVED" message:#"YOUR GRAPH HAS BEEN SAVEN IN THE PHOTO ALBUM" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
[maintimer invalidate];
time = 0;
}
[self bringThem]; //brings the buttons back
}
But now i need to get this image i created! I tried using the same code i use for the text:
-(IBAction)sendMail
{
(..)
//HERE IS WHERE THE NAME IS GIVEN
NSString *filename = [NSString stringWithFormat:#"%f.txt", [[NSDate date] timeIntervalSince1970]];
//THIS IS GOING TO STORE MY MESSAGE STUFF
NSString *content = [[NSMutableString alloc]init];
(...) //LOTS OF UNNECESSARY CODE
//HERE IS WHERE IT BILDS THE FILE
[self writeToTextFile:filename content:content];
//HERE IS THE CODE WHERE IT ATTACHES THE FILE
[self sendMailWithFile:filename];
//[content release];
}
-(void)sendMailWithFile : (NSString *)file
{
//THIS IS THE CODE THAT GETS THE TEXT
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/%#", documentsDirectory, file];
NSData *data = [[NSData alloc] initWithContentsOfFile:fileName];
//THIS WAS MY TRY TO GET THE PHOTO ON THE SAME STYLE OF THE TEXT
NSArray *photoPath = NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES);
NSString *photoDirectoryForFirstPhoto = [photoPath objectAtIndex:0];
NSString *photoName_First = [NSString stringWithFormat:#"%#/%#", photoDirectoryForFirstPhoto, /*I DO NOT HAVE THE PHOTO NAME*/#"FirstPhoto"];
NSData *photoData_First = [[NSData alloc] initWithContentsOfFile:photoName_First];
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
if ([MFMailComposeViewController canSendMail])
{
mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
[mailComposer setSubject:#"RK4 data"];
[mailComposer addAttachmentData:data mimeType:#"text/plain" fileName:#"[RK4][EQUATION][TEXT]"];
[mailComposer addAttachmentData:photoData_First mimeType:#"image/png" fileName:#"[RK4][EQUATION][IMAGE]"];
[mailComposer setMessageBody:#"iCalculus Runge-Kutta data." isHTML:NO];
[self presentModalViewController:mailComposer animated:YES];
}
else (...)
[mailComposer release];
[data release];
}
So that's my problem. I need to find a way to get the printscreen i took and attach it.
Because i need to come up with all the attaches in the email as soon as he clicks the "SEND MAIL" button.
Thanks.
Rather than saving to your photo library, you should save to documents directory, or tmp directory, to get documents directory you can use the following.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* dd = [paths objectAtIndex:0];
NSString *path = [dd stringByAppendingPathComponent:#"file.png"];
[UIImagePNGRepresentation(screenImage) writeToFile:path atomically:NO];
Take a look here for how to embed the image directly inside the email using base-64, that should be much cleaner than dumping temporary images to the users saved photos album.
Edit:
Category for handling base 64 with NSData, use the download towards the bottom.