Tuesday, June 26, 2007

Perl SMTP

IIS6 requires an Application Pool (like Sharepoint or Exchange) other than Default Application Pool for your Web or Virtual Directory for .Net mail sending via your webpage or else CDONTS library will throw Access Denied errors In Yer Face!

Well thanks to Perl's MIME-Lite and Net-SMTP you are likely to bypass this.

Code Snippet:

  1. use MIME::Lite;
  2. use Net::SMTP;
  3. # This debug flag will print debugging code to your browser,
  4. # depending on its value
  5. # Set this to 1 to send debug code to your browser.
  6. # Set it to 0 to turn it off.
  7. my $DEBUG = 1;
  8. if($DEBUG)
  9. {
  10. $| = 1;
  11. open(STDERR, ">&STDOUT");
  12. }
  13. # Set this variable to your smtp server name
  14. # my $ServerName = "YourSMTPServer";
  15. # Creat a new SMTP object
  16. #$smtp = Net::SMTP->new($ServerName, Debug => 1);
  17. # If you can't connect, don't proceed with the rest of the script
  18. #die "Couldn't connect to server" unless $smtp;
  19. ### Adjust Sender & Recepient email address
  20. my $from_address = '';
  21. my $to_address = '';
  22. my $cc_address = '';
  23. my $mime_type = 'multipart/mixed';
  24. ### Adjust subject and body message
  25. my $subject = '';
  26. my $message_body = "";
  27. ### Adjust the file to attach
  28. my $filename1 = '';
  29. my $recommended_filename1 = '';
  30. ### Creat the initial text of the message
  31. my $mime_msg = MIME::Lite->new(
  32. From => $from_address,
  33. To => $to_address,
  34. Cc => $cc_address,
  35. Subject => $subject,
  36. Type => $mime_type,
  37. )
  38. or die "Error creating MIME body: $!\n";
  39. ### Add the text message
  40. $mime_msg->attach(
  41. Type => 'TEXT',
  42. Data => $message_body
  43. ) or die "Error adding the text message part: $!\n";
  44. ### Attach the attachmnet file
  45. $mime_msg->attach(
  46. Type => 'application/txt',
  47. Path => $filename1,
  48. Filename => $recommended_filename1,
  49. Disposition => 'attachment',
  50. )
  51. or die "Error attaching test file: $!\n";
  52. my $message_body = $mime_msg->body_as_string();
  53. ### Set this variable to your smtp server name
  54. my $ServerName = "";
  55. ### Creat a new SMTP object
  56. $smtp = Net::SMTP->new($ServerName, Debug => 1);
  57. ### If you can't connect, don't proceed with the rest of the script
  58. die "Couldn't connect to server" unless $smtp;
  59. MIME::Lite->send('smtp', $ServerName, Timeout=>60);
  60. $mime_msg->send;
  61. ### Close the connection
  62. $smtp->quit();

If at first you fail, call it version 1.0

No comments: