使用Cocoa Scripting Bridge发送电子邮件

时间:2016-12-21 06:05:10

标签: objective-c macos email cocoa

使用Cocoa Scripting Bridge发送电子邮件,如何添加多个附件。

这是我的代码:

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

emailMessageL = [[[mail classForScriptingClass:@"outgoing message"] alloc] initWithProperties:
NSDictionary dictionaryWithObjectsAndKeys: [self.subjectField stringValue], @"subject", [self.messageContent stringValue], @"content", nil]];

[[mail outgoingMessages] addObject: emailMessageL];
emailMessageL.sender = [self.fromField stringValue];
emailMessageL.visible = YES;

if ( [mail lastError] != nil )
    return;

MailToRecipient *theRecipient = [[[mail classForScriptingClass:@"to recipient"] alloc] initWithProperties:
[NSDictionary dictionaryWithObjectsAndKeys:
                                      [self.toField stringValue], @"address",
                                      nil]];
[emailMessageL.toRecipients addObject: theRecipient];

if ( [mail lastError] != nil )
    return;

NSString *attachmentFilePath = aStrUrl ;

if ( [attachmentFilePath length] > 0 )
{
    MailAttachment *theAttachment;
    theAttachment = [[[mail classForScriptingClass:@"attachment"] alloc] initWithProperties: [NSDictionary dictionaryWithObjectsAndKeys: [[NSURL URLWithString:attachmentFilePath] path], @"fileName", nil]];

    [[emailMessageL.content attachments] addObject: theAttachment];

    if ( [mail lastError] != nil )
        return;
}

1 个答案:

答案 0 :(得分:0)

您会注意到您正在向attachments添加单个对象。它是一个可变数组,您可以添加其他对象。

例如,我在我的开发Macintosh上的/tmp目录中创建了四个文本文件,并且能够执行此操作:

for(int index=1; index<4; index++)
    {
        NSString *attachmentFilePath = [NSString stringWithFormat: @"/private/tmp/%d.txt", index];

        if ( [attachmentFilePath length] > 0 )
        {
            MailAttachment *theAttachment;
            theAttachment = [[[mail classForScriptingClass:@"attachment"] alloc] initWithProperties: [NSDictionary dictionaryWithObjectsAndKeys: [[NSURL URLWithString:attachmentFilePath] path], @"fileName", nil]];

            [emailMessageL.content.attachments addObject: theAttachment];

            if ( [mail lastError] != nil )
                return;
        }
    }

因此,在您的情况下,只需addObject:一个额外的附件,您就可以了。