I use this code to send an automated error message when something goes wrong, and it works fine, but it behaves a bit funny. I got the code from this SO question.
- (void)sendEmailWithMail:(NSString *) toAddress withSubject:(NSString *) subject Attachments:(NSArray *) attachments {
NSString *bodyText = @"Your body text \n\r";
NSString *emailString = [NSString stringWithFormat:@"\
tell application \"Mail\"\n\
set newMessage to make new outgoing message with properties {subject:\"%@\", content:\"%@\" & return} \n\
tell newMessage\n\
set visible to false\n\
set sender to \"%@\"\n\
make new to recipient at end of to recipients with properties {name:\"%@\", address:\"%@\"}\n\
tell content\n\
",subject, bodyText, @"McAlarm alert", @"McAlarm User", toAddress ];
//add attachments to script
for (NSString *alarmPhoto in attachments) {
emailString = [emailString stringByAppendingFormat:@"make new attachment with properties {file name:\"%@\"} at after the last paragraph\n\
",alarmPhoto];
}
//finish script
emailString = [emailString stringByAppendingFormat:@"\
end tell\n\
send\n\
end tell\n\
end tell"];
//NSLog(@"%@",emailString);
NSAppleScript *emailScript = [[NSAppleScript alloc] initWithSource:emailString];
[emailScript executeAndReturnError:nil];
[emailScript release];
/* send the message */
NSLog(@"Message passed to Mail");
}
It composes and sends a new message with the subject and body specified but it leaves the composed message open and i have to manually close the composed message as well as Mail itself.
Any ideas on how to tell Mail to close the mail and itself automatically?
It’s from my answer and it works fine for me.
My guess is there is an error somewhere in your code. Maybe a variable is not initialised or badly formatted?
Try to put the static Apple Script code into the Apple Script editor and run it to see whether it works there for you. If it does than it should be something wrong in your Obj-C code.