xcode 从可可发送电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5461648/
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 from Cocoa
提问by Lenny Magico
How can I send an email from a Cocoa app without using any email clients ? I have NSURL but it opens up an email client. I would like to send the email without this happening.
如何在不使用任何电子邮件客户端的情况下从 Cocoa 应用程序发送电子邮件?我有 NSURL 但它打开了一个电子邮件客户端。我想在没有发生这种情况的情况下发送电子邮件。
回答by bpds
Those response are outdated Mac OS X 10.8 and more you should use NSSharingService
这些响应是过时的 Mac OS X 10.8 和更多你应该使用 NSSharingService
NSArray *shareItems=@[body,imageA,imageB];
NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail];
service.delegate = self;
service.recipients=@[@"[email protected]"];
service.subject= [ NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"SLYRunner console",nil),currentDate];
[service performWithItems:shareItems];
回答by Tibidabo
UPDATE: As others suggested, from 10.9you can use NSSharingServicethat supports attachments as well!
更新:正如其他人所建议的,从10.9 开始,您也可以使用支持附件的NSSharingService!
Swift example:
快速示例:
let emailImage = NSImage.init(named: "ImageToShare")!
let emailBody = "Email Body"
let emailService = NSSharingService.init(named: NSSharingServiceNameComposeEmail)!
emailService.recipients = ["[email protected]"]
emailService.subject = "App Support"
if emailService.canPerform(withItems: [emailBody,emailImage]) {
// email can be sent
emailService.perform(withItems: [emailBody,emailImage])
} else {
// email cannot be sent, perhaps no email client is set up
// Show alert with email address and instructions
}
OLD UPDATE: My old answers worked fine until I had to sandbox my apps for the App Store.~~
Since then the only solution I found was using simply a mailto: link.
旧更新:我的旧答案运行良好,直到我不得不为 App Store 沙盒我的应用程序。~~从那时起,我找到的唯一解决方案就是使用简单的 mailto: 链接。
- (void)sendEmailWithMail:(NSString *) senderAddress Address:(NSString *) toAddress Subject:(NSString *) subject Body:(NSString *) bodyText {
NSString *mailtoAddress = [[NSString stringWithFormat:@"mailto:%@?Subject=%@&body=%@",toAddress,subject,bodyText] stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:mailtoAddress]];
NSLog(@"Mailto:%@",mailtoAddress);
}
Disadvantage: No attachment! If you know how to make it work on Mac let me know!
OLD ANSWER:You can Apple Script, Apple's scripting bridge framework (Solution 2) or a Python script (Solution 3)
Solution 1 (Apple script):
attachments is an array of stings containing file paths
- (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");
}
Solution 2 (Apple scriptingbridge framework):
You can use Apple's scriptingbridge framework to use Mail to send your message
Apple's exmaple linkit's pretty straightforward, you only need to fiddle with adding a rule and Mail.app to your project. Read Readme.txt carefully.
Change "emailMessage.visible = YES;" to "emailMessage.visible = NO;" so it sends it in the background.
Disadvantage: users need to have valid accounts under Mail.
Solution 3 (Python Script (no user account):
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 Solution 1 above directly), 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:
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
- (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;
}
}
- (void)sendEmailWithMail:(NSString *) senderAddress Address:(NSString *) toAddress Subject:(NSString *) subject Body:(NSString *) bodyText {
NSString *mailtoAddress = [[NSString stringWithFormat:@"mailto:%@?Subject=%@&body=%@",toAddress,subject,bodyText] stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:mailtoAddress]];
NSLog(@"Mailto:%@",mailtoAddress);
}
缺点:无附件!如果您知道如何在 Mac 上运行,请告诉我!
旧答案:您可以使用 Apple Script、Apple 的脚本桥接框架(解决方案 2)或 Python 脚本(解决方案 3)
解决方案 1(Apple 脚本):
附件是包含文件路径的字符串数组
- (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");
}
解决方案2(Apple scriptingbridge 框架):您可以使用Apple 的scriptingbridge 框架来使用Mail 发送您的消息
Apple 的示例链接非常简单,您只需要在项目中添加规则和Mail.app 即可。仔细阅读 Readme.txt。
更改“emailMessage.visible = YES;” 到“emailMessage.visible = NO;” 所以它在后台发送它。
缺点:用户需要在Mail下拥有有效的帐户。
解决方案3(Python脚本(无用户帐户):您也可以使用python脚本发送消息。缺点:用户必须输入SMTP详细信息,除非您从Mail中获取它们(但是您可以直接使用上面的解决方案1),或者你必须在你的应用程序中有一个可靠的 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()
我称之为使用 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 petert
This postshould help - it cites example codetoo.
You also need to change line 114 in Controller.m to send the message in the background:
您还需要更改 Controller.m 中的第 114 行以在后台发送消息:
emailMessage.visible = NO;
回答by Black Frog
You will need to use Simple Mail Transfer Protocol(SMTP). This link will give you a simply overview on how it works: Understanding the SMTP Protocol.
您将需要使用简单邮件传输协议(SMTP)。此链接将为您提供有关其工作原理的简单概述:了解 SMTP 协议。