Jump to content

Read Email Addresses from TXT File


CRC
 Share

Recommended Posts

I'm trying to use a script to send an email with some variables I pass to it through another program. I'm using a great email script I found here in the forums, but I'd like to be able to add recipients to this email without adding them to the script (since it needs to be compiled). How can I use an array to populate my $ToAddress variable for multiple email addresses? I know this is simple, but I've tried the help file and searching the forums with no luck. Thanks all

;##################################
; Include
;##################################
#Include<file.au3>
;##################################
; Variables
;##################################
$SmtpServer = "smtp.gmail.com"              ; address for the smtp-server to use - REQUIRED
$FromName = "----"                      ; name from who the email was sent
$FromAddress = "----" ; address from where the mail should come
$ToAddress =  "----"  ; destination address of the email - REQUIRED
$Subject = $CmdLine[1]                   ; subject from the email - can be anything you want it to be
$Body = $CmdLine[2] & @CRLF & $CmdLine[3] & @CRLF & $CmdLine[4] & @CRLF & $CmdLine[5] & @CRLF & $CmdLine[6] & @CRLF & @CRLF & $CmdLine[7]               ; the messagebody from the mail - can be left blank but then you get a blank mail
$AttachFiles = ""                       ; the file you want to attach- leave blank if not needed
$CcAddress = ""       ; address for cc - leave blank if not needed
$BccAddress = ""     ; address for bcc - leave blank if not needed
$Importance = "Normal"                  ; Send message priority: "High", "Normal", "Low"
$Username = "----"                    ; username for the account used from where the mail gets sent - REQUIRED
$Password = "----"                  ; password for the account used from where the mail gets sent - REQUIRED
;$IPPort = 25                            ; port used for sending the mail
;$ssl = 0                                ; enables/disables secure socket layer sending - put to 1 if using httpS
$IPPort=465                          ; GMAIL port used for sending the mail
$ssl=1                               ; GMAILenables/disables secure socket layer sending - put to 1 if using httpS

;##################################
; Script
;##################################
Global $oMyRet[2]
Global $oMyError = ObjEvent("AutoIt.Error", "MyErrFunc")
$rc = _INetSmtpMailCom($SmtpServer, $FromName, $FromAddress, $ToAddress, $Subject, $Body, $AttachFiles, $CcAddress, $BccAddress, $Importance, $Username, $Password, $IPPort, $ssl)
If @error Then
    MsgBox(0, "Error sending message", "Error code:" & @error & "  Description:" & $rc)
EndIf
;
; The UDF
Func _INetSmtpMailCom($s_SmtpServer, $s_FromName, $s_FromAddress, $s_ToAddress, $s_Subject = "", $as_Body = "", $s_AttachFiles = "", $s_CcAddress = "", $s_BccAddress = "", $s_Importance="Normal", $s_Username = "", $s_Password = "", $IPPort = 25, $ssl = 0)
    Local $objEmail = ObjCreate("CDO.Message")
    $objEmail.From = '"' & $s_FromName & '" <' & $s_FromAddress & '>'
    $objEmail.To = $s_ToAddress
    Local $i_Error = 0
    Local $i_Error_desciption = ""
    If $s_CcAddress <> "" Then $objEmail.Cc = $s_CcAddress
    If $s_BccAddress <> "" Then $objEmail.Bcc = $s_BccAddress
    $objEmail.Subject = $s_Subject
    If StringInStr($as_Body, "<") And StringInStr($as_Body, ">") Then
        $objEmail.HTMLBody = $as_Body
    Else
        $objEmail.Textbody = $as_Body & @CRLF
    EndIf
    If $s_AttachFiles <> "" Then
        Local $S_Files2Attach = StringSplit($s_AttachFiles, ";")
        For $x = 1 To $S_Files2Attach[0]
            $S_Files2Attach[$x] = _PathFull($S_Files2Attach[$x])
            ConsoleWrite('@@ Debug(62) : $S_Files2Attach = ' & $S_Files2Attach & @LF & '>Error code: ' & @error & @LF) ;### Debug Console
            If FileExists($S_Files2Attach[$x]) Then
                $objEmail.AddAttachment ($S_Files2Attach[$x])
            Else
                ConsoleWrite('!> File not found to attach: ' & $S_Files2Attach[$x] & @LF)
                SetError(1)
                Return 0
            EndIf
        Next
    EndIf
    $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = $s_SmtpServer
    If Number($IPPort) = 0 then $IPPort = 25
    $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = $IPPort
    ;Authenticated SMTP
    If $s_Username <> "" Then
        $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
        $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = $s_Username
        $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = $s_Password
    EndIf
    If $ssl Then
        $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
    EndIf
    ;Update settings
    $objEmail.Configuration.Fields.Update
    ; Set Email Importance
    Switch $s_Importance
        Case "High"
            $objEmail.Fields.Item ("urn:schemas:mailheader:Importance") = "High"
        Case "Normal"
            $objEmail.Fields.Item ("urn:schemas:mailheader:Importance") = "Normal"
        Case "Low"
            $objEmail.Fields.Item ("urn:schemas:mailheader:Importance") = "Low"
    EndSwitch
    $objEmail.Fields.Update
    ; Sent the Message
    $objEmail.Send
    If @error Then
        SetError(2)
        Return $oMyRet[1]
    EndIf
    $objEmail=""
EndFunc   ;==>_INetSmtpMailCom
;
;
; Com Error Handler
Func MyErrFunc()
    $HexNumber = Hex($oMyError.number, 8)
    $oMyRet[0] = $HexNumber
    $oMyRet[1] = StringStripWS($oMyError.description, 3)
    ConsoleWrite("### COM Error !  Number: " & $HexNumber & "   ScriptLine: " & $oMyError.scriptline & "   Description:" & $oMyRet[1] & @LF)
    SetError(1); something to check for when this function returns
    Return
EndFunc   ;==>MyErrFunc
Link to comment
Share on other sites

There are a few ways of doing it depending on the file you use to store the names.

The easiest is probably to read the file to an array and work from that.

FileContents (we'll call it addies.txt

me@something.net

This line won't match anything but the next one will

me@somethingElse.org

me@home.relaxing.com

$aArray = StringRegExp(FileRead(addies.txt"), "(?m:^)(\S+@\S+)(?:\v|\z)", 3)
If NOT @Error Then
   For $i = 0 to Ubound($aArray) -1
      MsgBox(0, "Result " & $1+1, $aArray[$i])
   Next
EndIf

George

Question about decompiling code? Read the decompiling FAQ and don't bother posting the question in the forums.

Be sure to read and follow the forum rules. -AKA the AutoIt Reading and Comprehension Skills test.***

The PCRE (Regular Expression) ToolKit for AutoIT - (Updated Oct 20, 2011 ver:3.0.1.13) - Please update your current version before filing any bug reports. The installer now includes both 32 and 64 bit versions. No change in version number.

Visit my Blog .. currently not active but it will soon be resplendent with news and views. Also please remove any links you may have to my website. it is soon to be closed and replaced with something else.

"Old age and treachery will always overcome youth and skill!"

Link to comment
Share on other sites

I'm assuming you just want a comma delimited string like turning an array of

User1@domain.com

User2@domain.com

User3@domain.com

User4@domain.com

Into a string like

User1@domain.com, User2@domain.com, User3@domain.com, User4@domain.com

Just take your array, I'll call it $addressArray, and use this

#include <array.au3>

_ArrayToString($addressArray, ", ")
Link to comment
Share on other sites

$File = FileOpen("test.txt", 0)

If $File = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

While 1
    $Line = FileReadLine($File)
    If @error = -1 Then ExitLoop

    $Email = StringRegExp($Line, "(.+@.+\..+)", 1)
    If @error = 0 Then
        MsgBox(0, "Email", $Email[0])
    EndIf
WEnd

FileClose($File)

Better to open the file, read it, then close it.

$Email[0] contains the email, if there is one.

Edited by darkjohn20
Link to comment
Share on other sites

I really hate to be stupid here but I tried incorporating each of these methods with no luck on any. The top of my script now appears as shown below, I get an error stating that no "To" addresses were defined. Could I trouble someone for a little more help?

;##################################
; Include
;##################################
#Include<file.au3>
;##################################
; Variables
;##################################

$File = FileOpen("addresses.txt", 0)

If $File = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

While 1
    $Line = FileReadLine($File)
    If @error = -1 Then ExitLoop

    $ToAddress = StringRegExp($Line, "(.+@.+\..+)", 1)
WEnd

$SmtpServer = "smtp.gmail.com"              ; address for the smtp-server to use - REQUIRED
$FromName = "----"                      ; name from who the email was sent
$FromAddress = "----" ; address from where the mail should come
;$ToAddress = $Email  ; destination address of the email - REQUIRED
$Subject = $CMDLINE[1]                   ; subject from the email - can be anything you want it to be
$Body = $CMDLINE[2]                              ; the messagebody from the mail - can be left blank but then you get a blank mail
$AttachFiles = ""                       ; the file you want to attach- leave blank if not needed
$CcAddress = ""       ; address for cc - leave blank if not needed
$BccAddress = ""     ; address for bcc - leave blank if not needed
$Importance = "Normal"                  ; Send message priority: "High", "Normal", "Low"
$Username = "----"                    ; username for the account used from where the mail gets sent - REQUIRED
$Password = "----"                  ; password for the account used from where the mail gets sent - REQUIRED
;$IPPort = 25                            ; port used for sending the mail
;$ssl = 0                                ; enables/disables secure socket layer sending - put to 1 if using httpS
$IPPort=465                          ; GMAIL port used for sending the mail
$ssl=1                               ; GMAILenables/disables secure socket layer sending - put to 1 if using httpS
Link to comment
Share on other sites

Now we're making progress! I think there's a problem with how the addresses are separated in my text file. They're just in a list using the carriage return, no commas or anything. My notification is going to the last email address on the list, but none of the others. Here's the top of my script currently:

#Include<file.au3>
;##################################
; Variables
;##################################

$File = FileOpen("addresses.txt", 0)

If $File = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

While 1
    $Line = FileReadLine($File)
    If @error = -1 Then ExitLoop

    $Email = StringRegExp($Line, "(.+@.+\..+)", 1)
WEnd


$SmtpServer = "smtp.gmail.com"              ; address for the smtp-server to use - REQUIRED
$FromName = "----"                      ; name from who the email was sent
$FromAddress = "----" ; address from where the mail should come
$ToAddress = $Email[0]
$Subject = $CMDLINE[1]                   ; subject from the email - can be anything you want it to be
$Body = $CMDLINE[2]                              ; the messagebody from the mail - can be left blank but then you get a blank mail
$AttachFiles = ""                       ; the file you want to attach- leave blank if not needed
$CcAddress = ""       ; address for cc - leave blank if not needed
$BccAddress = ""     ; address for bcc - leave blank if not needed
$Importance = "Normal"                  ; Send message priority: "High", "Normal", "Low"
$Username = "----"                    ; username for the account used from where the mail gets sent - REQUIRED
$Password = "----"                  ; password for the account used from where the mail gets sent - REQUIRED
;$IPPort = 25                            ; port used for sending the mail
;$ssl = 0                                ; enables/disables secure socket layer sending - put to 1 if using httpS
$IPPort=465                          ; GMAIL port used for sending the mail
$ssl=1                               ; GMAILenables/disables secure socket layer sending - put to 1 if using httpS

Link to comment
Share on other sites

The reason it only goes to the last email is you are not building a list but overwriting the $Email variable every time instead of appending to it.

Try Declaring...

$Email = ""

before the loop. Then use...

$Email &= StringRegExp($Line, "(.+@.+\..+)", 1) & ", "

To build the string instead. After your done you need to trim the last comma by

StringTrimRight($Email,1)

Also can I ask if you are trying to validate these email addresses first? Because if NOT, and all that is on each line is 1 email address, then you can do this in a simpler way.

Such as...

Dim $Email 
If Not _FileReadToArray("addresses.txt",$Email ) Then
   MsgBox(4096,"Error", " Error reading addresses.txt to Array     error:" & @error)
   Exit
EndIf
_ArrayDelete($Email,0)

Then later...

$ToAddress = _ArrayToString($addressArray, ", ")

Edit:

You will need to include.

#include <file.au3>

#include <array.au3>

for the method I described as an alternative.

Edited by ShawnW
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...