Отправить контактную форму поля в электронной почте - PullRequest
0 голосов
/ 11 февраля 2012

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

Ответы [ 2 ]

1 голос
/ 05 августа 2012

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

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

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

https://github.com/mikecheckDev/MDContactForm

0 голосов
/ 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:@"first@example.com", nil];
//    NSArray *ccRecipients = [[NSArray alloc] init];
//    NSArray *bccRecipients = [[NSArray alloc] init];
//    NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
//  NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", 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:first@example.com?cc=second@example.com,third@example.com&subject=Hello from California!";
NSString *body = @"&body=Feedback";

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

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
...