IPB     Il futuro di Tevac dipende da te!  

Benvenuto Visitatore ( Log In | Registrati )

  · · · · · · · · · · · ·
Reply to this topicStart new topic
> inviare mail con attchment da Cocoa, Come fare ad inviare una mail con un attachment usando Cocoa
germinara
messaggio 16 Jun 2008, 14:09
Messaggio #1


Level 2/11
**

Gruppo: Forum User
Messaggi: 75
Iscritto il: 6-April 05
Da: Pinerolo
Utente Nr.: 3.498



Ciao a tutti, mi trovo alle prese con un problemino "stupido", devo inviare in automatico da un Mac una mail ad un altro Mac, con in allegato un file.
L'invio della mail deve essere "trasparente" per l'utente, nel senso che il programma in Cocoa, deve aprire Mail, creare il messaggio, ed inviarlo ad uno specifico destinatario, quindi chiudere Mail, senza dover chiedere nulla all'utente (che potrebbe anche non essere presente in quanto schedulato in automatico).

Con Leopard, esiste un esempio di Apple, SBSendMail che utilizza la nuova tecnologia di Script Bridge ma questa non e' supportata da Tiger.
Essendo l'applicazione Cocoa realizzata per funzionare sia con Tiger che con Leopard e non volendo gestire due differenti versioni, ho pensato di indagare la strada di AppleScript.

Scopiazzando qui e la, (non sono per nulla in intenditore di AS) ho ricavato questo script che piu' o meno svolge il compito richiesto.

L'unico problema che mi rimane e' "se io metto l'istruzione quit per far chiudere Mail, il messaggio che ho creato mi rimane nella posta in uscita e quindi NON viene inviato.
la mia esigenza e' invece del tipo, INVIA il messaggio e quando hai fatto CHIUDI Mail. Ovviamente se non metto il quit, la mail viene inviata ma Mail mi rimane aperto."

Una volta sistemato lo script, lo potro' incapsulare e mandare in esecuzione da Cocoa.

Per lo meno, questa e' l'idea.

Suggerimenti ???

Francesco.

CODICE
set attachfiles to {"/Users/francescogerminara/Desktop/FGCAENDemo.pdf", "/Users/francescogerminara/Desktop/ObjC.pdf"}
tell application "Mail"
    set mailversion to version as string
    set msg to make new outgoing message at beginning of outgoing messages
    tell msg
        set the subject to "Prova"
        set the content to "Ciao questa e' una prova..."
        set sender to "franco@germinara.it"
        make new to recipient at end of to recipients with properties {name:"Monica", address:"monica.rossi@miaposta.com"}
        tell content
            repeat with attch in attachfiles
                make new attachment with properties {file name:attch} at after the last paragraph
            end repeat
        end tell
        
        set visible to true
    end tell
    activate
    send msg
    
    quit
end tell


Messaggio modificato da germinara il 16 Jun 2008, 14:13
Go to the top of the page
 
+Quote Post
germinara
messaggio 17 Jun 2008, 22:43
Messaggio #2


Level 2/11
**

Gruppo: Forum User
Messaggi: 75
Iscritto il: 6-April 05
Da: Pinerolo
Utente Nr.: 3.498



Ok, problema risolto.
Ecco il nuovo script.
Francesco.

CODE
set attachfiles to {"/Users/francescogerminara/Documents/Esportazione/fileprova.txt"}

tell application "Mail"
set msg to make new outgoing message at beginning of outgoing messages
tell msg
set the subject to "Prova"
set the content to "Ciao Monica e' una prova..."
set sender to "franco@germinara.it"
make new to recipient at end of to recipients with properties {name:"Monica", address:"info@germinara.it"}
tell content
repeat with attch in attachfiles
make new attachment with properties {file name:attch} at after the last paragraph
end repeat
end tell

set visible to false
end tell

tell application "System Events"
set visible of process "Mail" to false
end tell


repeat with m in outgoing messages
tell m to try
send
repeat while exists
delay 1
end repeat
exit repeat
end try
end repeat

repeat until (count outbox's messages) is 0
delay 2
end repeat

quit

end tell
Go to the top of the page
 
+Quote Post
chebfarid
messaggio 17 Jun 2008, 23:37
Messaggio #3


Level 8/11
********

Gruppo: Supporter
Messaggi: 3.660
Iscritto il: 11-July 03
Da: Milano
Utente Nr.: 395



Ho letto la tua richiesta solo ora ma vedo che hai già risolto - bravo ! icon_biggrin.gif

Ciao
Farid


--------------------
Abends lustig, morgens triste
das ist Leben von Artiste
Go to the top of the page
 
+Quote Post
germinara
messaggio 20 Jun 2008, 23:09
Messaggio #4


Level 2/11
**

Gruppo: Forum User
Messaggi: 75
Iscritto il: 6-April 05
Da: Pinerolo
Utente Nr.: 3.498



Grazie comunque.
icon_razz.gif


Per terminare il discorso, visto che il Topic era Attachment in Cocoa, ecco il metodo implementato per inviare la mail, utilizzando lo script descritto in precedenza (a cui ho apportato le necessarie modifiche per poter essere chiamato con una serie di argomenti dal codice cocoa).


Script finale
CODE
-- BY Francesco Germinara 20/6/2008

on sendmail(toDisplayName, toAddr, subj, body, attachfiles)

tell application "Mail"

set msg to make new outgoing message at beginning of outgoing messages
tell msg
set the subject to subj
set the content to body
make new to recipient at end of to recipients with properties {name:toDisplayName, address:toAddr}
tell content
repeat with attch in attachfiles
make new attachment with properties {file name:attch} at after the last paragraph
end repeat
end tell

set visible to false
end tell

tell application "System Events"
set visible of process "Mail" to false
end tell


repeat with m in outgoing messages
tell m to try
send
repeat while exists
delay 1
end repeat
exit repeat
end try
end repeat

repeat until (count outbox's messages) is 0
delay 2
end repeat

quit

end tell
end sendmail


Implementazione dei metodi in Cocoa per richiamare lo script con i vari parametri

Imposto i valori di default della finestra del programma
CODE
-(void)awakeFromNib{

[to setStringValue:@"info@germinara.it"];
[subject setStringValue:@"Test sending mail using Mail.App"];
[body setString:@"This is a sample of sending a mail from a Cocoa program using Mail application, using AppleScript."];
[attachment setStringValue:@""];
[prgBar setUsesThreadedAnimation:YES];
[prgBar setHidden:YES];

}




Metodo per Inviare la Mail


CODE
- (void)_runAppleScriptWithCommand:(NSString *)commandName
inScriptNamed:(NSString *)scriptName
withParameterDisplayName:(NSString *)strDisplayName
withParameterToAddr:(NSString *)strToAddr
withParameterSubject:(NSString *)strSubject
withParameterBody:(NSString *)strBody
withParameterAttachfiles:(NSString *)strAttachfiles
{

NSDictionary *errors = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:scriptName ofType:@"scpt"];
if ([path hasPrefix:@"/Volumes"])
return;
NSURL *url = [NSURL fileURLWithPath:path];
NSAppleScript *appleScript = [[NSAppleScript alloc] initWithContentsOfURL:url error:&errors];

/* See if there were any errors loading the script */
if (!appleScript || errors) {
NSLog(@"error creating applescript:%@ errors:%@", appleScript, [errors description]);
return;
}

NSAppleEventDescriptor *aParameter = nil;
NSAppleEventDescriptor *parameters = [NSAppleEventDescriptor listDescriptor];
aParameter = [NSAppleEventDescriptor descriptorWithString:strDisplayName];
[parameters insertDescriptor:aParameter atIndex:1];

aParameter = [NSAppleEventDescriptor descriptorWithString:strToAddr];
[parameters insertDescriptor:aParameter atIndex:2];

aParameter = [NSAppleEventDescriptor descriptorWithString:strSubject];
[parameters insertDescriptor:aParameter atIndex:3];

aParameter = [NSAppleEventDescriptor descriptorWithString:strBody];
[parameters insertDescriptor:aParameter atIndex:4];


NSAppleEventDescriptor *files = [NSAppleEventDescriptor listDescriptor];
[files insertDescriptor:[NSAppleEventDescriptor descriptorWithString:strAttachfiles] atIndex:1];

[parameters insertDescriptor:files atIndex:5];

ProcessSerialNumber psn = { 0, kCurrentProcess };
NSAppleEventDescriptor *target = [NSAppleEventDescriptor descriptorWithDescriptorType:typeProcessSerialNumber
bytes:&psn
length:sizeof(ProcessSerialNumber)];
NSAppleEventDescriptor *methodName = [NSAppleEventDescriptor descriptorWithString:[commandName lowercaseString]];
NSAppleEventDescriptor *event = [NSAppleEventDescriptor appleEventWithEventClass:'ascr'
eventID:'psbr'
targetDescriptor:target
returnID:kAutoGenerateReturnID
transactionID:kAnyTransactionID];
[event setParamDescriptor:methodName forKeyword:'snam'];
[event setParamDescriptor:parameters forKeyword:keyDirectObject];
NSAppleEventDescriptor *result = [appleScript executeAppleEvent:event error:&errors];
while (!result && !errors) {
int x = 1 + 1;
x ++;
}
if(errors) {
NSLog(@"error executing applescript: errors:%@", [errors description]);
}
[appleScript release];


}



Per chi fosse interessato al link http://www.germinara.it/download/FGSendMail.zip è possibile scaricare il programma di esempio ed i sorgenti.
Saluti, Francesco
Go to the top of the page
 
+Quote Post
sirguich_
messaggio 22 Jun 2008, 14:29
Messaggio #5


Più proxymizzato che mai
***********

Gruppo: Team Moderatori
Messaggi: 9.330
Iscritto il: 18-March 04
Da: Ripa (LU)
Utente Nr.: 1.649



Grazie per aver condiviso questo codice. Sono sicuro potrà servire a qualcuno.


--------------------
Emanuele Personale | Blog | Facebook | LinkedIn
Supporta Tevac!

"The competent programmer is fully aware of the limited size of his own skull. He therefore approaches his task with full humility, and avoids clever tricks like the plague." - Edsger W. Dijkstra
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic

 

Collapse

> 

    Titolo discussione Risposte Autore discussione Visite Ultima azione
No New Posts   5 mabal 68 4 September 2008 - 19:45
Ultimo messaggio di: mabal
No New Posts   2 gatto 60 4 September 2008 - 12:36
Ultimo messaggio di: gpz500
No New Posts   5 ibowe 52 3 September 2008 - 14:19
Ultimo messaggio di: sirguich_
No New Posts   6 vocenarrante 114 29 August 2008 - 20:38
Ultimo messaggio di: vocenarrante
No new   14 fcde 257 28 August 2008 - 23:49
Ultimo messaggio di: poweruser
No New Posts   0 Marco Coïsson 57 19 August 2008 - 10:12
Ultimo messaggio di: Marco Coïsson
No New Posts   7 NoHere 150 18 August 2008 - 11:38
Ultimo messaggio di: macdvd
No New Posts   3 Mad_Biker 116 16 August 2008 - 11:26
Ultimo messaggio di: Mad_Biker
No New Posts   5 SoHo 155 14 August 2008 - 11:07
Ultimo messaggio di: SoHo
No New Posts   5 Martini 97 11 August 2008 - 11:37
Ultimo messaggio di: maxrainato
No New Posts   2 Danny 101 8 August 2008 - 00:01
Ultimo messaggio di: macdvd
No new   19 fabris 200 5 August 2008 - 17:59
Ultimo messaggio di: fabris

Modalità di visualizzazione: Normale · Passa a: Lineare · Passa a: Outline


RSS Versione Lo-Fi Oggi è il: 6 September 2008 - 00:37
IP.Board Skin Developed By Creative Networks