Perl读取文件并发送电子邮件

时间:2016-07-19 11:06:16

标签: perl

我有一个格式低于

的日志文件
D12345 joe@gmail.com
C67890 mary@gmail.com
B45678 don@gmail.com
A12309 joe@gmail.com
F45670 mary@gmail.com
F45470 joe@gmail.com

目前,我可以向拥有以下电子邮件正文内容的所有人发送电子邮件

your Product id: $product_id

($ product_id是D12345,A12309,F45470,C67890,F45670)

如果用户的电子邮件ID在日志文件中出现 N 次,则会向用户发送“ N ”电子邮件。

示例: 2封电子邮件发送至mary@gmail.com,3封电子邮件发送至joe@gmail.com

如果单个电子邮件ID在输出文件中多次出现,我希望只向用户发送一封电子邮件,但拥有所有产品ID,例如

your Product ids: C67890, F45670 to mary@gmail.com

your Product ids: D12345, A12309, F45470 to joe@gmail

我当前的代码段

open my $fh, '<', "output.txt" or die "could not open file: $!";
while (my $line = <$fh>) { 
    my ($product_id, $to_email) = $line =~ /(\w\d+)\t(\S+)/;

my $MailFrom = 'myemail@domain.com'; 
my $subject = "PRODUCT ID DETAILS"; 
my $message = "your Product ids: $product_id";

%mail = ( 
To => $to_email, 
From => $MailFrom,   
Subject => $subject, 
Message => $message 
); 

$mail{Smtp} = 'mail.myorg.com';

sendmail(%mail)or die $Mail::Sendmail::error;
}
close $fh;

建议真的很感激。提前谢谢。

2 个答案:

答案 0 :(得分:3)

您必须在发送邮件之前将日志文件中的信息聚合为哈希

这里有一些示例代码转储%mail哈希而不是调用sendmail,以便您可以看到结果

use strict;
use warnings 'all';

use Data::Dump;

my %users;

{
    open my $fh, '<', "output.txt" or die "could not open file: $!";

    while ( <$fh> ) { 
        my ($prod, $user) = split;
        push @{ $users{$user} }, $prod;
    }
}

# Convert arrays of product codes into comma-separated strings
#
$_ = join ', ', @$_ for values %users;

while ( my ($user, $prods) = each %users ) {

    my %mail = (
        To      => $user,
        From    => 'myemail@domain.com',
        Subject => 'PRODUCT ID DETAILS',
        Message => "Your product IDs: $prods",
        Smtp    => 'mail.myorg.com',
    );

    dd \%mail

    #sendmail(%mail) or die $Mail::Sendmail::error;
}

输出

{
  From => "myemail\@domain.com",
  Message => "Your product IDs: D12345, A12309, F45470",
  Smtp => "mail.myorg.com",
  Subject => "PRODUCT ID DETAILS",
  To => "joe\@gmail.com",
}
{
  From => "myemail\@domain.com",
  Message => "Your product IDs: B45678",
  Smtp => "mail.myorg.com",
  Subject => "PRODUCT ID DETAILS",
  To => "don\@gmail.com",
}
{
  From => "myemail\@domain.com",
  Message => "Your product IDs: C67890, F45670",
  Smtp => "mail.myorg.com",
  Subject => "PRODUCT ID DETAILS",
  To => "mary\@gmail.com",
}

答案 1 :(得分:0)

这不是一个perl问题,只是如何进行基本编码。

我会预处理数据以满足您的需求,即使用电子邮件ID作为密钥创建数组哈希并将产品推送到数组中。

你最终会得到类似的东西:

{
    joe@gmail.com: ['D12345', 'A12309', 'F45470'],
    mary@gmail.com: ['C67890', 'F45670'],
    don@gmail.com: ['B45678']
}

从日志文件创建数据结构后,对每个密钥进行迭代并创建一个包含值的电子邮件应该非常简单。