2011-03-28 9 views
12

이메일 클라이언트를 사용하지 않고 Cocoa 앱에서 이메일을 보내려면 어떻게해야합니까? 나는 NSURL을 가지고 있지만 전자 메일 클라이언트를 엽니 다. 이런 일이 발생하지 않고 이메일을 보내고 싶습니다.코코아에서 이메일 보내기

+0

중복 가능성 = 오래된을 사용해야합니다. 송수신 메일 프레임 워크] (http://stackoverflow.com/questions/3567251/pantomime-outdated-sending-and-receiving-mail-framework) –

+0

가능한 중복 [이메일 전송 - 코코아] (http : // stackoverflow. com/questions/1396229/send-email-cocoa) –

답변

24

UPDATE : 다른 사람이 10.9에서 제안한 것처럼 당신은뿐만 아니라 첨부 파일을 지원하는 NSSharingService을 사용할 수 있습니다!

스위프트 예 :

OLD UPDATE

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 

    } 
을 :. 내가 앱 스토어 내 애플리케이션을 샌드 박스했다 때까지 내 오랜 답변이 괜찮 았는데 ~ 를 내가 찾은 다음 유일한 해결책 때문에 사용되었다 간단히 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); 
} 

단점 : 첨부 파일 없음! Mac에서 작동하도록하는 방법을 알고 있다면 알려주십시오!

OLD 답변 : 당신은 애플 스크립트, 애플의 스크립트 다리 프레임 워크 (해결 방법 2) 또는 파이썬 스크립트 (해결 방법 3)

해결 방법 1 (애플 스크립트) 할 수 있습니다

첨부 배열입니다 파일 경로를 포함하는 침의

- (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"); 

}

SOLU 제 2 절 (Apple scriptingbridge 프레임 워크) : Apple의 scriptingbridge 프레임 워크를 사용하여 Mail을 사용하여 메시지 보내기
Apple's exmaple link 매우 간단합니다. 규칙과 Mail.app를 프로젝트에 추가하기 만하면됩니다. Readme.txt를주의 깊게 읽으십시오.

변경 "emailMessage.visible = YES;" ~ "emailMessage.visible = NO;" 그래서 그것을 배경으로 보냅니다.

단점 : 사용자는 메일 아래에 유효한 계정이 있어야합니다.

해결 방법 3 (Python 스크립트 (사용자 계정 없음) : ) 파이썬 스크립트를 사용하여 메시지를 보낼 수도 있습니다. 단점 : 메일에서 메일을 가져 오지 않으면 (직접 솔루션 1을 사용할 수 있음) 또는 신뢰할 수있는 SMTP 릴레이를 앱에 하드 코딩해야하는 경우가 아니라면 SMTP 세부 정보를 입력해야합니다 (Gmail 계정을 설정하고 사용 가능). 를 사용하여 이메일을 보내려면이 방법을 형성

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() 

그리고 내가 전화 : 당신의 애플 리케이션이 너무 많은 이메일을 보낼 경우는 그 목적을 위해, 그러나 구글 계정 (SPAM))
내가이 파이썬 스크립트를 사용하여 삭제할 수 있습니다 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; 
     } 
    } 

도움이 되길 바랍니다.

+1

Scripting Bridge ... Thunderbird를 사용하면 어떨까요? 아니면 Outlook? 또는 다른 것? –

+0

그러면 펄 스크립트를 사용할 수 있습니다. Mail이 가장 많이 사용되는 전자 메일 클라이언트입니다 (없는 경우). 사용자에게 SMTP 세부 정보를 입력하도록 요청하거나 전자 메일을 하드 코드 할 수 있습니다. – Tibidabo

+0

** Perl ** 스크립트의 첫 번째 줄은 #!/usr/bin/env python ??? :-P –

3

post은 도움이됩니다. example code도 인용해야합니다.

는 또한 백그라운드에서 메시지를 보낼 라인 (114) Controller.m에서 변경해야합니다

emailMessage.visible = NO; 
+0

이전에 그 게시물을 보았습니다.하지만 실제로 원하지 않는 이메일을 끝낼 때 메일 응용 프로그램을 열었습니다. 나 자신의 메일 응용 프로그램을 만들고 싶습니다. :) 그러나 감사합니다. D –

26

그 응답은 오래된 맥 OS X 10.8 그리고 더는 NSSharingService

[판토마임의
NSArray *[email protected][body,imageA,imageB]; 
NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail]; 
service.delegate = self; 
[email protected][@"[email protected]"]; 
service.subject= [ NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"SLYRunner console",nil),currentDate]; 
[service performWithItems:shareItems]; 

The sharing service documentation page

+1

이 대답이 수용되어야합니다. 사용자가 Outlook을 사용하는 경우 첨부 파일이 첨부되지 않습니다. – fzwo

+0

NSSharingService의 또 다른 문제점은 작곡가의 전자 메일 본문을 미리 설정할 수 없다는 것입니다 (필요한 경우). –

+3

@ZS 올바르지 않습니다. 메시지 본문을 설정하려면 performWithItems :를 참조하십시오. – insys