Отправить поля контактной формы в электронной почте

У меня есть контактная форма, состоящая из текстовых полей (5 полей), которые я хотел бы отправить по электронной почте на один адрес электронной почты. Как мне это сделать в xCode?


person Michael Zucker    schedule 11.02.2012    source источник
comment
Уже ответили до SO   -  person Joel Kravets    schedule 11.02.2012


Ответы (2)


Для тех, кто наткнется на этот вопрос, вы можете использовать эту контактную форму iOS.

Это хорошо соответствует моим потребностям, оно использует компонент PHP для фактической отправки электронной почты. (пример сценария включен в образец проекта.

Я разместил его на Github здесь:

https://github.com/mikecheckDev/MDContactForm

person MikecheckDev    schedule 05.08.2012
comment
Большое спасибо, что поделились этим, это здорово! :-) - person kernix; 25.11.2012

Связанный пост имеет аналогичный ответ, но я добавляю свой код, так как он уже проверяет canSendMail. Я также оставил кучу закомментированного кода, который упрощает добавление других материалов в электронное письмо.

Обратите внимание, что это значительно проще, если вы ориентируетесь только на iOS 5.

У меня есть бесплатное приложение QCount, в котором используется этот код. В самом деле, я надеюсь, что удалил все нестандартное из моего копирования и вставки :-) http://itunes.apple.com/ng/app/qcount/id480084223?mt=8

Наслаждаться,

Дэмиен

В вашем .h:

#import <MessageUI/MessageUI.h>

Методы в вашем .m:

- (void)emailLabelPressed { // or whatever invokes your email
// Create a mail message in the user's preferred mail client
// by opening a mailto URL.  The extended mailto URL format
// is documented by RFC 2368 and is supported by Mail.app
// and other modern mail clients.
//
// This routine's prototype makes it easy to connect it as
// the action of a user interface object in Interface Builder.
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if (mailClass != nil)
{
    // We must always check whether the current device is configured for sending emails
    if ([mailClass canSendMail])
    {
        [self displayComposerSheet];
    }
    else
    {
        [self launchMailAppOnDevice];
    }
}
else
{
    [self launchMailAppOnDevice];
}
}

-(void)displayComposerSheet {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"Your Form Subject"];

// Take screenshot and attach (optional, obv.)
UIImage *aScreenshot = [self screenshot];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(aScreenshot)];
[picker addAttachmentData:imageData mimeType:@"image/png" fileName:@"screenshot"];

// Set up the recipients.
NSArray *toRecipients = [NSArray arrayWithObjects:@"[email protected]", nil];
//    NSArray *ccRecipients = [[NSArray alloc] init];
//    NSArray *bccRecipients = [[NSArray alloc] init];
//    NSArray *ccRecipients = [NSArray arrayWithObjects:@"[email protected]", @"[email protected]", nil];
//  NSArray *bccRecipients = [NSArray arrayWithObjects:@"[email protected]", nil];

[picker setToRecipients:toRecipients];
//    [picker setCcRecipients:ccRecipients];
//    [picker setBccRecipients:bccRecipients];

// Attach an image to the email.
/*    NSString *path = [[NSBundle mainBundle] pathForResource:@"ipodnano"
 ofType:@"png"];
 NSData *myData = [NSData dataWithContentsOfFile:path];
 [picker addAttachmentData:myData mimeType:@"image/png"
 fileName:@"ipodnano"];
 */ 
// Fill out the email body text.
//    NSString *emailBody = @"Use this for fixed content.";

NSMutableString *emailBody = [[NSMutableString alloc] init];
[emailBody setString: @"Feedback"];
// programmatically add your 5 fields of content here.

[picker setMessageBody:emailBody isHTML:NO];
// Present the mail composition interface.
if ([self respondsToSelector:@selector(presentViewController:animated:completion:)]) {
    [self presentViewController:picker animated:YES completion:nil];
}  else {
    [self presentModalViewController:picker animated:YES];
}
}

- (void)mailComposeController:(MFMailComposeViewController *)controller
      didFinishWithResult:(MFMailComposeResult)result
                    error:(NSError *)error {
if ([self respondsToSelector:@selector(dismissViewControllerAnimated:completion:)]) {
    [self dismissViewControllerAnimated:YES completion:nil];
}  else {
    [self dismissModalViewControllerAnimated:YES];
}
}

-(void)launchMailAppOnDevice {
NSString *recipients = @"mailto:[email protected][email protected],[email protected]&subject=Hello from California!";
NSString *body = @"&body=Feedback";

NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
person Damien Del Russo    schedule 11.02.2012