如何在文件名中查找字符串并通过电子邮件发送该文件?

时间:2018-04-19 19:26:09

标签: powershell

我有一个包含多个PDF文件的文件夹。它们在文件名中有一个唯一的标识符,即两个字符。示例:XYZ_A1_123.pdf,XYZ_QQ_456.pdf等.A1和QQ是标识符。

标识符与特定电子邮件地址匹配。我有一个CSV文件,有两列,ID和匹配的电子邮件地址。我无法让我的脚本查找该特定标识符并发送该文件。如果PDF文件只有名称中的标识符,例如" A1.pdf",则脚本可以正常工作。到目前为止,这是我的代码。另外,我正在寻找添加进度条但不确定如何。任何帮助表示赞赏。谢谢!

$csv = Import-Csv "," -path C:\Test\emails.csv -header "id","email"

foreach ($item in $csv) {
$filename = "$($item.id).pdf"
}

$emailSmtpServer = "smtp.gmail.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "email@address.com"
$emailSmtpPass = "mypassword"

$emailFrom = "me@address.com"
$emailTo = $item.email

$emailMessage = New-Object System.Net.Mail.MailMessage( $emailFrom , $emailTo )
$emailMessage.Subject = "This is the subject" 
#$emailMessage.IsBodyHtml = $true #true or false depends
$emailMessage.Body = "This is the body."
$emailMessage.Attachment = $filename
$emailMessage.Attachments.add($filename)

$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , 
$emailSmtpServerPort )
$SMTPClient.EnableSsl = $True
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( 
$emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )

1 个答案:

答案 0 :(得分:1)

使用代码和电子邮件地址创建测试文件以模仿您描述的文件:

        InputFilter filter = (source, start, end, dest, dstart, dend)->{
        for (int i = start; i < end; i++) {
            char symbol = source.charAt(i);
            if (!isValidCharacter(symbol)) {
                StringBuilder buf = new StringBuilder();
                for(int j = start; j < end; j++)
                {
                    symbol = source.charAt(j);
                    if(isValidCharacter(symbol)) buf.append(symbol);
                }
                return buf.toString();
            }
        }
        return null;
    };

以下代码段将提取文件的代码,将其与地址列表进行比较,并检索电子邮件地址(如果存在):

echo "AF,a@p.com" > test.csv
echo "QC,q@p.com" >> test.csv
cat .\test.csv

看起来你已经锁定了电子邮件,所以我不会在这里重复一遍。如果您找到匹配的地址,我只会发送电子邮件。