Advertisement
snakerdlk

Direct smtp client

Oct 14th, 2011
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.29 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use Net::DNS;
  7. use Net::SMTP;
  8.  
  9. #argv to from subject message
  10. if($#ARGV+1 != 4){
  11.     print "Usage: script.pl to from subject message\n";
  12.     exit 1;
  13. }
  14.  
  15. my $to = $ARGV[0];
  16. my $from = $ARGV[1];
  17. my $subject = $ARGV[2];
  18. my $msg = $ARGV[3];
  19.  
  20. my $domain = "";
  21. if($to =~ m/\@(.+)$/){
  22.     $domain = $1;
  23. }else{
  24.     die "Could not get domain from '$to'\n";
  25. }
  26.  
  27. my %mx = ();
  28.  
  29. my $res = Net::DNS::Resolver->new;
  30. my $query = $res->query($domain, "MX");
  31.  
  32. my @result = $query->answer;
  33. print "found ".(@result)." mx entries for '$domain'\n";
  34. if(@result){
  35.     foreach  my $rr (@result){
  36.         $mx{$rr->exchange} = $rr->preference;
  37.         print $rr->preference." - ".$rr->exchange."\n";
  38.     }
  39. }else{
  40.     die "Can't find MX records for '$domain': ", $res->errorstring, "\n";
  41. }
  42.  
  43. my $sent = 0;
  44. my @mailhosts = sort { $mx{$a} cmp $mx{$b} } keys %mx;
  45. foreach my $host(@mailhosts){
  46.     print "Connecting to $host...\n";
  47.     my $smtp = Net::SMTP->new($host) or next;
  48.     $smtp->hello('mailhost');
  49.     $smtp->mail($from);
  50.     $smtp->to($to);
  51.     $smtp->data();
  52.     $smtp->datasend("Subject: $subject\r\n");
  53.     $smtp->datasend("From: $from\r\n");
  54.     $smtp->datasend("To: $to\r\n");
  55.     $smtp->datasend("$msg");
  56.    
  57.     $smtp->dataend();
  58.     $sent = 1;
  59.     last;
  60. }
  61.  
  62. if(!$sent){
  63.     die("Could not send email...");
  64. }
  65.  
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement