使用Cocoa Scripting Bridge在事先不知道收件人的情况下发送电子邮件

时间:2011-05-31 17:28:26

标签: objective-c cocoa scripting-bridge

我使用默认Apple提供的SBSendEmail示例代码发送电子邮件。我的情况唯一的区别是我事先不知道收件人,我希望用户在邮件窗口的收件人字段中输入收件人。这是我的代码:

    MailApplication *mail = [SBApplication
                             applicationWithBundleIdentifier:@"com.apple.Mail"];        

    /* create a new outgoing message object */
    MailOutgoingMessage *emailMessage =
    [[[mail classForScriptingClass:@"outgoing message"] alloc]
     initWithProperties:
     [NSDictionary dictionaryWithObjectsAndKeys:
      @"this is my subject", @"subject",
      @"this is my content", @"content",
      nil]];

    /* add the object to the mail app  */
    [[mail outgoingMessages] addObject: emailMessage];

    /* set the sender, show the message */
    //  emailMessage.sender = [self.fromField stringValue];
    emailMessage.visible = YES;

    /* create a new recipient and add it to the recipients list */
//        MailToRecipient *theRecipient =
//        [[[mail classForScriptingClass:@"to recipient"] alloc]
//         initWithProperties:
//         [NSDictionary dictionaryWithObjectsAndKeys:
//          @"recipientEmailHere@example.com", @"address",
//          nil]];
//        [emailMessage.toRecipients addObject: theRecipient];


    /* add an attachment, if one was specified */
    NSString *attachmentFilePath = "<my provided file path>";
    if ( [attachmentFilePath length] > 0 ) {

        /* create an attachment object */
        MailAttachment *theAttachment = [[[mail
                                           classForScriptingClass:@"attachment"] alloc]
                                         initWithProperties:
                                         [NSDictionary dictionaryWithObjectsAndKeys:
                                          attachmentFilePath, @"fileName",
                                          nil]];

        /* add it to the list of attachments */
        [[emailMessage.content attachments] addObject: theAttachment];
    }
    /* send the message */
    [emailMessage send];

由于我未指定收件人,因此邮件应用程序会打开一条提示错误的警告,您尚未指定任何收件人。虽然此警报只有一个“编辑消息”按钮,然后用户可以使用该按钮添加收件人。是否有可能此警报无法打开?

1 个答案:

答案 0 :(得分:1)

你可以尝试

[emailMessage open];

将导致Mail.app在撰写窗口中打开您的邮件。

要使Mail.app成为最前面的应用程序,以便用户可以看到新创建的消息窗口,请使用:

 [mail activate];