• Publicidad

Enviar correo desde Perl

¿Apenas comienzas con Perl? En este foro podrás encontrar y hacer preguntas básicas de Perl con respuestas aptas a tu nivel.

Re: Enviar correo desde Perl

Notapor explorer » 2011-05-06 14:34 @648

Mira: los módulos de la familia Email::Send::* son antiguos, y algunos no funcionan bien. Por eso, los autores de módulos crearon la familia Email::Sender::*, que es más moderna, con menos errores y más funcionalidad.

Por otra parte... si se trata de enviar correos a Gmail, CPAN me dice que el módulo más moderno para enviarlos es Email::Send::SMTP::Gmail. Si lo instalas, no necesitarás más que este módulo y estos otros:

use Net::SMTP::SSL;
use MIME::Base64;
use File::Spec;
use LWP::MediaTypes;

de los cuales, me parece que File::Spec y MIME::Base64 ya los tendrás instalados de base. Yo creo que es la solución más sencilla y cómoda, para ti, para mandar correos desde tu máquina.

Mira el ejemplo en la sinopsis del módulo, para que veas que el modo de crear correos, adjuntos, y enviarlos, es casi igual a los otros módulos.

Es recomendable siempre usar los módulos más modernos, ya que a veces los protocolos o formas de acceder van cambiando con el tiempo. Y si, además, lo ha hecho un tal Juan José San Martín, pues seguro que también puede resolverte alguna duda :)
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14477
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Publicidad

Re: Enviar correo desde Perl

Notapor noa86 » 2011-05-06 15:10 @674

Muchas gracias por el módulo, pero me sigue dando error en la conexión SMTP.

Could not connect to SMTP server

No sé cuál puede ser el problema... ¿Puede que tenga que configurar algo en Fedora? No se me ocurre cuál puede ser el problema...

¿Puede ser el problema que trabajo con localhost?
noa86
Perlero nuevo
Perlero nuevo
 
Mensajes: 93
Registrado: 2010-11-15 14:43 @655

Re: Enviar correo desde Perl

Notapor explorer » 2011-05-06 19:42 @862

Aunque trabajes en localhost, tu estás indicando el nombre de servidor al que tiene que conectarse, para enviar el correo.

¿Seguro que tienes acceso a Internet? Es decir, desde la línea de comandos, con el comando ping, ¿se conecta?

Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
explorer@casa:~/Documentos/Desarrollo/perl> ping smtp.gmail.com
PING gmail-smtp-msa.l.google.com (209.85.227.109) 56(84) bytes of data.
64 bytes from wy-in-f109.1e100.net (209.85.227.109): icmp_req=1 ttl=53 time=120 ms
64 bytes from wy-in-f109.1e100.net (209.85.227.109): icmp_req=2 ttl=53 time=200 ms
^C
--- gmail-smtp-msa.l.google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 120.895/160.676/200.458/39.783 ms
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4


Mira, he hecho la prueba en mi máquina:
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
casa:/usr/lib/perl5 # cpanp install Email::Send::SMTP::Gmail
[MSG] Checking if source files are up to date
[MSG] Updating source file '01mailrc.txt.gz'
[MSG] Trying to get 'ftp://ftp.rediris.es/mirror/CPAN/authors/01mailrc.txt.gz'
[MSG] Updating source file '03modlist.data.gz'
[MSG] Trying to get 'ftp://ftp.rediris.es/mirror/CPAN/modules/03modlist.data.gz'
[MSG] Updating source file '02packages.details.txt.gz'
[MSG] Trying to get 'ftp://ftp.rediris.es/mirror/CPAN/modules/02packages.details.txt.gz'
[MSG] No '/root/.cpanplus/custom-sources' dir, skipping custom sources
[MSG] Rebuilding author tree, this might take a while
[MSG] Rebuilding module tree, this might take a while
[MSG] No '/root/.cpanplus/custom-sources' dir, skipping custom sources
[MSG] No '/root/.cpanplus/custom-sources' dir, skipping custom sources
Installing Email::Send::SMTP::Gmail (0.22)
[MSG] Trying to get 'ftp://ftp.rediris.es/mirror/CPAN/authors/id/P/PE/PECO/Email-Send-SMTP-Gmail-0.22.tar.gz'
[MSG] Trying to get 'ftp://ftp.rediris.es/mirror/CPAN/authors/id/P/PE/PECO/CHECKSUMS'
[MSG] Checksum matches for 'Email-Send-SMTP-Gmail-0.22.tar.gz'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/META.yml'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/t/'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/t/00-load.t'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/t/pod-coverage.t'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/t/manifest.t'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/t/pod.t'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/MANIFEST'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/Changes'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/lib/'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/lib/Email/'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/lib/Email/Send/'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/lib/Email/Send/SMTP/'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/lib/Email/Send/SMTP/Gmail.pm'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/Makefile.PL'
[MSG] Extracted 'Email-Send-SMTP-Gmail-0.22/README'
[MSG] Extracted 'Email::Send::SMTP::Gmail' to '/root/.cpanplus/5.12.3/build/Email-Send-SMTP-Gmail-0.22'
Running [/usr/bin/perl /usr/bin/cpanp-run-perl /root/.cpanplus/5.12.3/build/Email-Send-SMTP-Gmail-0.22/Makefile.PL]...
Checking if your kit is complete...
Looks good
Warning: prerequisite Net::SMTP_auth 0 not found.
Writing Makefile for Email::Send::SMTP::Gmail
[MSG] Module 'Email::Send::SMTP::Gmail' requires 'Net::SMTP_auth' version '0' to be installed

Module 'Email::Send::SMTP::Gmail' requires 'Net::SMTP_auth' to be installed

If you don't wish to see this question anymore
you can disable it by entering the following commands on the prompt:
    '
s conf prereqs 1; s save'


  1> Yes
  2> No
  3> Yes to all (for this module)
  4> No to all  (for this module)

Should I install this module? [1]: 3
[MSG] Trying to get '
ftp://ftp.rediris.es/mirror/CPAN/authors/id/A/AP/APLEINER/Net-SMTP_auth-0.08.tar.gz'
[MSG] Trying to get '
ftp://ftp.rediris.es/mirror/CPAN/authors/id/A/AP/APLEINER/CHECKSUMS'
[MSG] Checksum matches for '
Net-SMTP_auth-0.08.tar.gz'
[MSG] Extracted '
Net-SMTP_auth-0.08/'
[MSG] Extracted '
Net-SMTP_auth-0.08/eg/'
[MSG] Extracted '
Net-SMTP_auth-0.08/eg/smtp-tester.pl'
[MSG] Extracted '
Net-SMTP_auth-0.08/SMTP_auth.pm'
[MSG] Extracted '
Net-SMTP_auth-0.08/README'
[MSG] Extracted '
Net-SMTP_auth-0.08/Changes'
[MSG] Extracted '
Net-SMTP_auth-0.08/test.pl'
[MSG] Extracted '
Net-SMTP_auth-0.08/Makefile.PL'
[MSG] Extracted '
Net-SMTP_auth-0.08/MANIFEST'
[MSG] Extracted '
Net::SMTP_auth' to '/root/.cpanplus/5.12.3/build/Net-SMTP_auth-0.08'
Running [/usr/bin/perl /usr/bin/cpanp-run-perl /root/.cpanplus/5.12.3/build/Net-SMTP_auth-0.08/Makefile.PL]...
Checking if your kit is complete...
Looks good
Writing Makefile for Net::SMTP_auth
Running [/usr/bin/make]...
cp SMTP_auth.pm blib/lib/Net/SMTP_auth.pm
Manifying blib/man3/Net::SMTP_auth.3pm
Running [/usr/bin/make test]...
PERL_DL_NONLAZY=1 /usr/bin/perl "-Iblib/lib" "-Iblib/arch" test.pl
1..1
ok 1
Running [/usr/bin/make install]...
Installing /usr/lib/perl5/site_perl/5.12.3/Net/SMTP_auth.pm
Installing /usr/share/man/man3/Net::SMTP_auth.3pm
Appending installation info to /usr/lib/perl5/5.12.3/i586-linux-thread-multi/perllocal.pod
Running [/usr/bin/make]...
cp lib/Email/Send/SMTP/Gmail.pm blib/lib/Email/Send/SMTP/Gmail.pm
Manifying blib/man3/Email::Send::SMTP::Gmail.3pm
Running [/usr/bin/make test]...
PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, '
blib/lib', 'blib/arch')" t/*.t
# Testing Email::Send::SMTP::Gmail 0.22, Perl 5.012003, /usr/bin/perl
t/00-load.t ....... ok
t/manifest.t ...... skipped: Author tests not required for installation
t/pod-coverage.t .. skipped: Test::Pod::Coverage 1.08 required for testing POD coverage
t/pod.t ........... skipped: Test::Pod 1.22 required for testing POD
All tests successful.
Files=4, Tests=1,  1 wallclock secs ( 0.06 usr  0.03 sys +  0.30 cusr  0.05 csys =  0.44 CPU)
Result: PASS
Running [/usr/bin/make install]...
Installing /usr/lib/perl5/site_perl/5.12.3/Email/Send/SMTP/Gmail.pm
Installing /usr/share/man/man3/Email::Send::SMTP::Gmail.3pm
Appending installation info to /usr/lib/perl5/5.12.3/i586-linux-thread-multi/perllocal.pod
*** Install log written to:
  /root/.cpanplus/install-logs/Email-Send-SMTP-Gmail-0.22-1304728468.log

Module '
Email::Send::SMTP::Gmail' installed successfully
No errors installing all modules

casa:/usr/lib/perl5 #
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4
He escrito este programa:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2.  
  3. use Email::Send::SMTP::Gmail;
  4.  
  5. my $mail=Email::Send::SMTP::Gmail->new(
  6.     -smtp=>'gmail.com',
  7.     -login=>'[email protected]',
  8.     -pass=>'contraseña',
  9. );
  10.  
  11. $mail->send(
  12.     -to=>'miotra@dirección.de.correo.com',
  13.     -subject=>'Hello!',
  14.     -verbose=>'1',
  15.     -body=>'Just testing it',
  16. #    -attachments=>'full_path_to_file',
  17. );
  18.  
  19. $mail->bye;
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
y sale:
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
explorer@casa:~/Documentos/Desarrollo> ./kk.pl
Attachments successfully verified
With No attachments
Sending email
Mail sent!
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
y, a los pocos segundos, me llegó el correo.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14477
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Enviar correo desde Perl

Notapor noa86 » 2011-05-07 04:29 @228

Puedo hacer ping sin problemas, y he copiado el código a un archivo en mi escritorio. He ejecutado desde terminal ./email.pl y me sale lo mismo que a ti, y me ha llegado también el correo a la perfección.

El error me sale al ejecutarlo en el navegador, con http://localhost/cgi-bin/email.pl

[Sat May 07 11:24:34 2011] [error] [client x.x.x.x] Could not connect to SMTP server
[Sat May 07 11:24:34 2011] [error] [client x.x.x.x] Premature end of script headers: email.pl
noa86
Perlero nuevo
Perlero nuevo
 
Mensajes: 93
Registrado: 2010-11-15 14:43 @655

Re: Enviar correo desde Perl

Notapor explorer » 2011-05-07 06:07 @296

A ver... una cosa es ejecutar un programa en la línea de comandos y otra bien distinta, como si fuera un CGI.

Para ejecutar como CGI, el programa debe enviar un preámbulo al navegador del usuario, para que sepa qué es lo que está recibiendo.

Eso es justo lo que dice la segunda línea del error.

Solo tienes que poner un

print "Content-type: text/html\n\n";

o un

print "Content-type: text/plain\n\n";

nada más empezar el programa.
(Más información, en la sección Tutoriales / CGI de este sitio web, en la parte de arriba de esta página.)

En cuanto al primer error, parece ser que sale de la línea 32 del módulo, indicando que no se ha podido conectar al servidor de correo. Veo también, en esa línea, que hay una opción para activar el modo de depurado en el módulo Net::SMTP::SSL, así que ahí te puede dar más información.

Las primeras líneas del programa quedarían ahora:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2.  
  3. use Email::Send::SMTP::Gmail;
  4.  
  5. print "Content-type: text/plain\n\n";
  6.  
  7. my $mail=Email::Send::SMTP::Gmail->new(
  8.     -smtp   => 'gmail.com',
  9.     -login  => '[email protected]',
  10.     -pass   => 'contraseña',
  11.     -debug  => 1,
  12. );
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Con el debug activado, verás más información del momento de la conexión, y así podrías saber por qué sale error.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14477
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Enviar correo desde Perl

Notapor noa86 » 2011-05-07 06:18 @304

He activado el debug pero no me muestra nada más que el mismo error :
Could not connect to SMTP server.
noa86
Perlero nuevo
Perlero nuevo
 
Mensajes: 93
Registrado: 2010-11-15 14:43 @655

Re: Enviar correo desde Perl

Notapor explorer » 2011-05-07 06:28 @311

Pues a mí me sale un montón de información:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
explorer@casa:~/Documentos/Desarrollo> ./kk.pl
Net::SMTP::SSL>>> Net::SMTP::SSL(1.01)
Net::SMTP::SSL>>>   IO::Socket::SSL(1.38)
Net::SMTP::SSL>>>     IO::Socket::INET6(2.67)
Net::SMTP::SSL>>>       IO::Socket(1.31)
Net::SMTP::SSL>>>         IO::Handle(1.28)
Net::SMTP::SSL>>>           Exporter(5.64_01)
Net::SMTP::SSL>>>   Net::Cmd(2.29)
Net::SMTP::SSL=GLOB(0x864f81c)<<< 220 mx.google.com ESMTP g58sm2001529wen.20
Net::SMTP::SSL=GLOB(0x864f81c)>>> EHLO localhost.localdomain
Net::SMTP::SSL=GLOB(0x864f81c)<<< 250-mx.google.com at your service, [87.220.26.155]
Net::SMTP::SSL=GLOB(0x864f81c)<<< 250-SIZE 35882577
Net::SMTP::SSL=GLOB(0x864f81c)<<< 250-8BITMIME
Net::SMTP::SSL=GLOB(0x864f81c)<<< 250-AUTH LOGIN PLAIN XOAUTH
Net::SMTP::SSL=GLOB(0x864f81c)<<< 250 ENHANCEDSTATUSCODES
Net::SMTP::SSL=GLOB(0x864f81c)>>> AUTH LOGIN
Net::SMTP::SSL=GLOB(0x864f81c)<<< 334 VXNlDF5hbWU6
Net::SMTP::SSL=GLOB(0x864f81c)>>> amZlcdjs9AZ21haWwuY29t
Net::SMTP::SSL=GLOB(0x864f81c)<<< 334 UGFzcsdfcmQ6
Net::SMTP::SSL=GLOB(0x864f81c)>>> T2hjsdfdlzaDA1
Net::SMTP::SSL=GLOB(0x864f81c)<<< 235 2.7.0 Accepted
Attachments successfully verified
Net::SMTP::SSL=GLOB(0x864f81c)>>> MAIL FROM:<[email protected]>
Net::SMTP::SSL=GLOB(0x864f81c)<<< 250 2.1.0 OK g58sm2001529wen.20
Net::SMTP::SSL=GLOB(0x864f81c)>>> RCPT TO:<[email protected]>
Net::SMTP::SSL=GLOB(0x864f81c)<<< 250 2.1.5 OK g58sm2001529wen.20
Net::SMTP::SSL=GLOB(0x864f81c)>>> DATA
Net::SMTP::SSL=GLOB(0x864f81c)<<< 354  Go ahead g58sm2001529wen.20
Net::SMTP::SSL=GLOB(0x864f81c)>>> From: [email protected]
Net::SMTP::SSL=GLOB(0x864f81c)>>> To: [email protected]
Net::SMTP::SSL=GLOB(0x864f81c)>>> Reply-To: [email protected]
Net::SMTP::SSL=GLOB(0x864f81c)>>> Subject: Hello!
With No attachments
Net::SMTP::SSL=GLOB(0x864f81c)>>> MIME-Version: 1.0
Net::SMTP::SSL=GLOB(0x864f81c)>>> Content-Type: text/plain
Net::SMTP::SSL=GLOB(0x864f81c)>>> Just testing it
Net::SMTP::SSL=GLOB(0x864f81c)>>> .
Net::SMTP::SSL=GLOB(0x864f81c)<<< 250 2.0.0 OK 1304766222 g58sm2001529wen.20
Sending email
Mail sent!
Net::SMTP::SSL=GLOB(0x864f81c)>>> QUIT
Net::SMTP::SSL=GLOB(0x864f81c)<<< 221 2.0.0 closing connection g58sm2001529wen.20
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

Quizás el problema esté en otro sitio... pero sin más información, es muy difícil de averiguar.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14477
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Enviar correo desde Perl

Notapor noa86 » 2011-05-07 06:46 @323

Si hago:

[root@localhost cgi-bin]# ./email.pl

sí me sale todo lo que te ha salido a ti. Y se envía el email, pero el problema me da al ejecutarlo en el navegador.

¿No será por algún tema de Apache o así?
noa86
Perlero nuevo
Perlero nuevo
 
Mensajes: 93
Registrado: 2010-11-15 14:43 @655

Re: Enviar correo desde Perl

Notapor explorer » 2011-05-07 07:45 @365

¿Sale alguna información en los ficheros de log del servidor web? Ahí sí que debería salir algo.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14477
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Enviar correo desde Perl

Notapor noa86 » 2011-05-07 08:19 @388

Yo en el que miro es en error_log. ¿Hay algún otro donde mirar?
noa86
Perlero nuevo
Perlero nuevo
 
Mensajes: 93
Registrado: 2010-11-15 14:43 @655

AnteriorSiguiente

Volver a Básico

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 3 invitados

cron