macos 发送电子邮件 - 可可
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1396229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send Email - Cocoa
提问by lab12
How would I be able to send emails using Cocoa? Which framework would I use, and how would I use it.
如何使用 Cocoa 发送电子邮件?我将使用哪个框架,以及我将如何使用它。
回答by Tibidabo
I think using an Apple script is the simplest solutions. I use it when the user has an account set up in Mail.
我认为使用 Apple 脚本是最简单的解决方案。当用户在邮件中设置了帐户时,我会使用它。
Apple script:
苹果脚本:
attachments is an array of stings containing file paths.
附件是包含文件路径的字符串数组。
"set visible to true" if you want the message to pop up before sending
如果您希望消息在发送前弹出,请“设置可见为真”
- (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");
}
}
Disadvantage: users need to have valid accounts under Mail.
缺点:用户需要在Mail下拥有有效帐户。
Python Script (if no user account under mail):
You can also use a python script to send a message.
Disadvantage: users have to enter SMTP details unless you grab them from Mail (but then you can use the apple script above ), or you have to have a reliable SMTP relay hardcoded in your app (you can set up a gmail account and use it for that purpose, however if your apps send too many emails google can delete your account (SPAM))
I use this python script:
Python 脚本(如果邮件下没有用户帐户):您也可以使用 Python 脚本发送消息。缺点:用户必须输入 SMTP 详细信息,除非您从 Mail 中获取它们(但是您可以使用上面的苹果脚本),或者您必须在您的应用程序中具有可靠的 SMTP 中继(您可以设置一个 gmail 帐户并使用它)为此,但是如果您的应用程序发送太多电子邮件谷歌可以删除您的帐户(垃圾邮件))
我使用这个 python 脚本:
import sys
import smtplib
import os
import optparse
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
username = sys.argv[1]
hostname = sys.argv[2]
port = sys.argv[3]
from_addr = sys.argv[4]
to_addr = sys.argv[5]
subject = sys.argv[6]
text = sys.argv[7]
password = getpass.getpass() if sys.stdin.isatty() else sys.stdin.readline().rstrip('\n')
message = MIMEMultipart()
message['From'] = from_addr
message['To'] = to_addr
message['Date'] = formatdate(localtime=True)
message['Subject'] = subject
#message['Cc'] = COMMASPACE.join(cc)
message.attach(MIMEText(text))
i = 0
for file in sys.argv:
if i > 7:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(file, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
message.attach(part)
i = i + 1
smtp = smtplib.SMTP(hostname,port)
smtp.starttls()
smtp.login(username, password)
del password
smtp.sendmail(from_addr, to_addr, message.as_string())
smtp.close()
And I call it form this method to send an email using a gmail account
我称之为使用 gmail 帐户发送电子邮件的这种方法
- (bool) sendEmail:(NSTask *) task toAddress:(NSString *) toAddress withSubject:(NSString *) subject Attachments:(NSArray *) attachments {
NSLog(@"Trying to send email message");
//set arguments including attachments
NSString *username = @"[email protected]";
NSString *hostname = @"smtp.gmail.com";
NSString *port = @"587";
NSString *fromAddress = @"[email protected]";
NSString *bodyText = @"Body text \n\r";
NSMutableArray *arguments = [NSMutableArray arrayWithObjects:
programPath,
username,
hostname,
port,
fromAddress,
toAddress,
subject,
bodyText,
nil];
for (int i = 0; i < [attachments count]; i++) {
[arguments addObject:[attachments objectAtIndex:i]];
}
NSData *passwordData = [@"myGmailPassword" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *environment = [NSDictionary dictionaryWithObjectsAndKeys:
@"", @"PYTHONPATH",
@"/bin:/usr/bin:/usr/local/bin", @"PATH",
nil];
[task setEnvironment:environment];
[task setLaunchPath:@"/usr/bin/python"];
[task setArguments:arguments];
NSPipe *stdinPipe = [NSPipe pipe];
[task setStandardInput:stdinPipe];
[task launch];
[[stdinPipe fileHandleForReading] closeFile];
NSFileHandle *stdinFH = [stdinPipe fileHandleForWriting];
[stdinFH writeData:passwordData];
[stdinFH writeData:[@"\n" dataUsingEncoding:NSUTF8StringEncoding]];
[stdinFH writeData:[@"Description" dataUsingEncoding:NSUTF8StringEncoding]];
[stdinFH closeFile];
[task waitUntilExit];
if ([task terminationStatus] == 0) {
NSLog(@"Message successfully sent");
return YES;
} else {
NSLog(@"Message not sent");
return NO;
}
}
I hope it helps
我希望它有帮助
回答by Brandon Bodnar
Apple's Developer Connection has a sample project called SBSendEmail which demonstrates how to use a Scripting Bridge to send email via scripting to the Mail app.
Apple 的 Developer Connection 有一个名为 SBSendEmail 的示例项目,它演示了如何使用脚本桥通过脚本将电子邮件发送到邮件应用程序。
You can download the whole projectand run it in XCode to see how it works. Of particular interest to you will be the sendEmailMessage: method in Controller.m
您可以下载整个项目并在 XCode 中运行它以查看它是如何工作的。您特别感兴趣的是Controller.m 中的 sendEmailMessage: 方法
回答by Garrett
You can use opening the default mail clientor you can use a framework. This should get you started.
回答by Peter Hosey
For Growl 1.2, I wrote a Python-based mail-sending program, which the MailMe display runs using NSTask.
对于 Growl 1.2,我编写了一个基于 Python 的邮件发送程序,MailMe 显示使用 NSTask 运行该程序。
I did this largely out of dissatisfaction with the other mail frameworks for Cocoa, most of which also support receiving mail, which is unnecessary for something output-only like MailMe.
我这样做主要是因为对 Cocoa 的其他邮件框架不满意,其中大部分也支持接收邮件,这对于像 MailMe 这样只输出的东西是不必要的。
回答by NSResponder
Check out:
查看:
http://www.collaboration-world.com/pantomime
http://www.collaboration-world.com/pantomime
I haven't looked at it in several years, but when I was at Apple I advocated that we include it with the OS to replace the mail functionality we'd lost in the NeXT/Apple transition.
我已经好几年没看过它了,但是当我在 Apple 时,我主张我们将它包含在操作系统中,以取代我们在 NeXT/Apple 过渡中丢失的邮件功能。