Making a script universal

I am a newby to Applescript, my question is very similar to one I just answered in a topic before.

But am very confused:

I try this:



set myFile2 to alias "Macintosh HD:Users:username:Desktop:NameList.txt"

set myFile2 to ((path to home folder) & "Desktop:NameList.txt")

open myFile2


I am trying to make my script funcitonal to any computer, or user name.

The second line would be a replacement for the first one. But the second line doesn’t work.

Please:

What am I doing wrong?

myFile2 in the second and third lines is a list. First you need to change the ‘path to’ reference to a string, then you need to specify that it is a file in the ‘open’ statement.

set myFile2 to (path to desktop folder as text) & “Name.txt”
tell app “Finder” to open file myFile2

or: tell app “Finder” to open alias myFile2
or: … item myFile2
or: … document file myFile2

As long as the item exists, any of these will work.

There are several ways to do this.

set myFile2 to ((path to current user folder as text) & "Desktop:NameList.txt")
tell application "Finder" to open alias myFile2
tell application "Finder"
	set myFile2 to ((home as text) & "Desktop:NameList.txt")
	open alias myFile2
end tell
tell application "Finder" to open file "NameList.txt" of desktop
set ptd to path to desktop as text
tell application "Finder" to open file (ptd & "NameList.txt")

– Rob

Try using the “path to desktop” constant from the scripting additions, instead of the path to home folder (that way you’ll have to type less :slight_smile: ). You have to set the path to a string, otherwise Applescript will concantenate the two parts into a list. Take a look at the result when you do this:

set pathToFile  to (path to desktop) & "NameList.txt"

You will get this:
{alias “Macintosh HD:Users:username:Desktop:”, “NameList.txt”}
Coerce the path to a string, concantenate the two strings, then coerce back to an alias. Then it will work.

set  deskPath to  (path to desktop) as string
set pathtoFile to (deskPath & "NameList.txt") as alias

Hi Guys!

Thanks for posting!

It seems my prblem is more specific to my Script than I thought.

I tried to give a simple example of my dificulty. But none of the solutions posted works.

This is my full code:



(*

Applescript escrito por Bernardo Höhl em 05 de Abril de 2004
Contém partes de Applescripts de Apple Computer

Com usa-lo:

Coloque a Pasta "EnviarEmailsPostfix" no seu Desktop.

Para rodar este script você precisar ter o "PostfixEnabler1.0.sitx.hqx" instalado em 
seu computador, que, habilita o sendmail do seu Unix.

Não mexa na posição das subpastas.


*)

-- Aqui você declara dois arquivos de texto onde vai armazenar os endereços de email e nomes dos destinatários:

set myFile to alias "Macintosh HD:Users:fundidor:Desktop:EnviarEmailsPostfix:BancoDados:ListaEmails.txt"

-- This works:
set myFile2 to alias "Macintosh HD:Users:fundidor:Desktop:EnviarEmailsPostfix:BancoDados:ListaNomes.txt"

-- This doesn't work:

--set myFile2 to ((path to current user folder as text) & "EnviarEmailsPostfix:BancoDados:ListaNomes.txt") as alias


-- Escolher um destinatário de uma lista ou incluir um novo:


set pergunta1 to display dialog "Quer escolher um email, ou incluir novo email?" buttons {"escolher", "incluir"}

if button returned of pergunta1 is "escolher" then
	
	
	--Aqui o script lê o conteudo dos arquivos de texto, e monta uma lista de Nomes:
	
	
	open for access myFile
	set fileText to read myFile
	close access myFile
	
	open for access myFile2
	set fileText2 to read myFile2
	close access myFile2
	
	set myList to fileText
	
	set myList2 to fileText2
	
	set x to the count the paragraphs in fileText
	set y to the count the paragraphs in fileText2
	
	
	set EmailList to paragraphs 1 thru x of myList
	
	set NomeList to paragraphs 1 thru y of myList2
	
	--set EmailList to EmailList as list
	
	--set NomeList to NomeList as list
	
	set EscolherNome to choose from list NomeList with prompt ¬
		"Escolha um destinatário:" without multiple selections allowed
	
	
	if the EscolherNome is false then return "user cancelled"
	set the destinatario to ¬
		item (list_position((EscolherNome as string), NomeList)) of the EmailList
	
else
	
	-- Pergunta o nome do destinatário:
	
	
	set meuTexto2 to display dialog "Escreva aqui o nome do Destinatário:" default answer "Nome do infeliz" buttons "Ok" default button "Ok"
	
	set meuTexto2 to text returned of meuTexto2 as string
	set meuTexto2 to meuTexto2 & return
	
	-- Grava no arquivo de texto o nome do destinatário:
	
	
	my write_to_file(meuTexto2, myFile2)
	open for access myFile
	set fileText to read myFile
	close access myFile
	
	
	repeat
		
		-- Grava no arquivo de texto o endereço de email do destinatário:
		
		
		set meuTexto to display dialog "Escreva aqui o endereço de email:" default answer "" buttons "Ok" default button "Ok"
		
		set meuTexto to text returned of meuTexto as string
		
		
		-- Se contém lixo, repete:
		
		if meuTexto contains " " or "/" or "," then
			display dialog "Você digitou um endereço de email inválido!"
		else
			
			if meuTexto does not contain "@" then
				display dialog "Você digitou um endereço de email inválido!"
			else
				set meuTexto to meuTexto & return
				
				my write_to_file(meuTexto, myFile)
				
				open for access myFile
				set fileText to read myFile
				close access myFile
				
				open for access myFile2
				set fileText2 to read myFile2
				close access myFile2
				
				set myList to fileText
				
				set myList2 to fileText2
				
				set x to the count the paragraphs in fileText
				set y to the count the paragraphs in fileText2
				
				
				set EmailList to paragraphs 1 thru x of myList
				
				set NomeList to paragraphs 1 thru y of myList2
				
				set EmailList to EmailList as list
				
				set NomeList to NomeList as list
				
				set EscolherNome to choose from list NomeList with prompt ¬
					"Escolha um destinatário:" without multiple selections allowed
				
				
				if the EscolherNome is false then return "user cancelled"
				set the destinatario to ¬
					item (list_position((EscolherNome as string), NomeList)) of the EmailList
				
				exit repeat
			end if
		end if
		
	end repeat
	
	
end if

set meuCorpo to display dialog "Qual é o texto do email?" default answer "" buttons "Ok" default button "Ok" with icon 1


-- Corrige os caracteres especiais do português para linguagem HTML:


set meuCorpo to replace_chars(meuCorpo, "á", "&")
set meuCorpo to replace_chars(meuCorpo, "á", "&")
set meuCorpo to replace_chars(meuCorpo, "é", "&")
set meuCorpo to replace_chars(meuCorpo, "í", "&")
set meuCorpo to replace_chars(meuCorpo, "ó", "&")
set meuCorpo to replace_chars(meuCorpo, "ú", "&")


set meuCorpo to replace_chars(meuCorpo, "ç", "&")
set meuCorpo to replace_chars(meuCorpo, "ã", "&")
set meuCorpo to replace_chars(meuCorpo, "Ã", "Ã")
set meuCorpo to replace_chars(meuCorpo, "õ", "&")
set meuCorpo to replace_chars(meuCorpo, "Õ", "Õ")
set meuCorpo to replace_chars(meuCorpo, "ö", "&")
set meuCorpo to replace_chars(meuCorpo, "ê", "&")
set meuCorpo to replace_chars(meuCorpo, "ô", "&")
set meuCorpo to replace_chars(meuCorpo, "à", "&")


set meuCorpo to replace_chars(meuCorpo, return, "<BR>")


-- Remove lixo da String:

set meuCorpo to text 1 thru -11 of meuCorpo


--Monta o cabeçario do email:


set meuCorpo to "From: Bernardo Hohl <fundidor_postifix@mydomain.com.br>
Subject: Mensagem enviada pelo servidor postfix (de Bernardo Hoehl)
To: <" & destinatario & ">
X-Mailer: Bernardo’s Mailer Version 1.0
Organization: Usina Brasileira de Cristobalita Ltda - Rio de Janeiro - Brazil
Content-Type: text/html; charset=ISO-8859-1

<html>
" & meuCorpo & "
</html>
."


set ArquivoTemporario to "arquivo_temporario.tmp"


set CaminhoArquivo to ((path to home folder) & ":Desktop:EnviarEmailsPostFix:" & ArquivoTemporario)

my write_to_file(meuCorpo, CaminhoArquivo)



set Comando to "sendmail -bm " & destinatario & " < ~/Desktop/EnviarEmailsPostfix/" & ArquivoTemporario

tell application "Terminal"
	do shell script Comando
end tell
tell application "Terminal"
	
	activate
	
	tell application "Terminal"
		
		activate
		
		if custom title of window 1 does not contain "Atividade" then
			with timeout of 1800 seconds
				do script with command "tail -f /var/log/mail.log"
				tell window 1
					
					set background color to "black"
					set cursor color to "white"
					set normal text color to "green"
					set bold text color to "red"
					set title displays shell path to true
					set title displays window size to true
					set title displays device name to true
					set title displays file name to true
					set title displays custom title to true
					set custom title to "Atividade do Send Mail"
					set number of columns to 113
					set number of rows to 9
					--set position to 0
					--set window bounds to 200
					-- set origin to 400
					
				end tell
				
				tell window 2
					close
				end tell
			end timeout
			say "See the Send Mail log!"
		else
			
			say "See the Send Mail log!"
			
		end if
	end tell
end tell


on write_to_file(this_data, target_file)
	try
		set the target_file to the target_file as text
		set the open_target_file to open for access file target_file with write permission
		write this_data to the open_target_file starting at eof
		close access the open_target_file
	on error
		try
			close access file target_file
		end try
	end try
end write_to_file

on list_position(this_item, this_list)
	repeat with i from 1 to the count of this_list
		if item i of this_list is this_item then return i
	end repeat
	return 0
end list_position


(*
on list_positions(this_list, this_item, list_all)
	set the offset_list to {}
	repeat with i from 1 to the count of this_list
		if item i of this_list is this_item then
			set the end of the offset_list to i
			if list_all is false then return item 1 of offset_list
		end if
	end repeat
	if list_all is false and offset_list is {} then return 0
	return the offset_list
end list_positions

*)

on replace_chars(this_text, search_string, replacement_string)
	set AppleScript's text item delimiters to the search_string
	set the item_list to every text item of this_text
	set AppleScript's text item delimiters to the replacement_string
	set this_text to the item_list as string
	set AppleScript's text item delimiters to ""
	return this_text
end replace_chars

delay 5

do shell script "rm ~/Desktop/EnviarEmailsPostFix/arquivo_temporario.tmp"

return Comando



The problem is related to the statement " open for acccess my File"

fundidor, you do know that these two lines are not equivalent:

The first one points to a folder on the desktop, the second point to a folder in the current user’s folder.
When AppleScript compiles a script that has an alias specified, AppleScript looks for that file on the disk. It has to exist in the exact spot specified, else an error is returned.
The EnviarEmailsPostfix folder is in the Desktop folder. The second line tell AS to look in the user’s folder for the folder EnviarEmailsPostfix and doesn’t find it (since it’s not in the user’s folder, it’s in the Desktop folder) so AS throws an error.
These lines would be equivalent (assuming you are logged in):

set myFile2 to alias "Macintosh HD:Users:fundidor:Desktop:EnviarEmailsPostfix:BancoDados:ListaNomes.txt"
set myFile2 to ((path to desktop as text) & "EnviarEmailsPostfix:BancoDados:ListaNomes.txt") as alias

Remember, the user’s folder is not the desktop folder.

Yes Dennis!

You are right!

I posted a wrong statement.

This is because I have been trying all sorts of things.

But it still doens’t work If I point the path the correct way.

Try it.

Still confused…

I tried deleting my text files and creating new empty ones with the same name and put in the “BancoDados” folder.

Once this is done I get the same error message I got when I try the statement “path to bla bla folder”…

I recovered the old files put in the right place and the script is functional again.

Why?