Batch sending an email - email

I am making a program using batch and upon a crash or an error it will make a text file called debug.txt. I need to know if there is a way of emailing this file automatically using batch to the following email address "something#example.com". debug.txt is in the same location as the batch file. Does anyone know a code I could use. It must not have any extra softwere.

I see 3 options for you as of now:
1. The bottom line is there's no built-in way in batch, but there are third-party tools like blat etc. that can be called from a batch file, but as you have mentioned you don't want any extra software.
2. You can enable the installed SMTP Server of Windows. And then run a Powershell script:
$smtpServer = "system.abc.com"
$smtpFrom = "dontreply#abc.com"
$smtpTo = "something#abc.com"
$messageSubject = "Put your subject here"
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.IsBodyHTML = $true
$message.Body = Get-Content debug.txt
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)
3. You can enable the installed SMTP Server of Windows. And then run a VBScript:
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const FileToBeUsed = "debug.txt"
Dim objCDO1
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(FileToBeUsed, ForReading)
Set objCDO1 = CreateObject("CDO.Message")
objCDO1.Textbody = f.ReadAll
f.Close
objCDO1.TO ="something#abc.com"
objCDO1.From = "dontreply#abc.com"
objCDO1.Subject = "Put your subject here"
objCDO1.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration /sendusing") = 2
objCDO1.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration /smtpserver") = "system.abc.com"
objCDO1.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration /smtpserverport") = 25
objCDO1.Configuration.Fields.Update
objCDO1.Send
Set f = Nothing
Set fso = Nothing
As you have mentioned that you are using Windows 7 ultimate so both option 2 and 3 will work on your system very well.

You can use free tool like sendemail.exe http://caspian.dotconf.net/menu/Software/SendEmail/. Download and copy sendemail.exe to system path. This is only for simple internal SMTP messages. This cannot be used to send external messages unless your Exchange server is setup to send anonymous external messages. Almost all Exchange servers are not setup to do this.
You can use this simple routine in the batch script.
CALL:SENDEMAILALERT "From SMTP address" "To SMTP addresses" "Subject" "Message" "File to attach" "smtp.host.com:25"
:SENDEMAILALERT
SET SENDEMAILCMD=-f "%~1"
SET SENDEMAILCMD=%SENDEMAILCMD% -t "%~2"
SET SENDEMAILCMD=%SENDEMAILCMD% -u "%~3"
SET SENDEMAILCMD=%SENDEMAILCMD% -m "%~4"
SET SENDEMAILCMD=%SENDEMAILCMD% -a "%~5"
SET SENDEMAILCMD=%SENDEMAILCMD% -s "%~6"
SENDEMAIL %SENDEMAILCMD% >NUL 2>&1
SET SENDEMAILCMD=
GOTO:EOF

Related

Release Artifacts delivered to user group as an attachment in email

I work with build and release in VSTS. I use Copy Files option in my Build definition and copy the Artifacts in a folder. I want that the Artifacts ( .exe, .dll, .zip etc)created at the end of the release must be attached in an email and must be delivered to a list of email addresses.
How this can be achieved.
Use archive task to zip the files and use powershell script given below to send an email with attachment.
Now use Powershell task and paste following script. Please edit SMTP and email settings.
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "Youremail#gmail.com"
$Password = "Pass#1"
$to = "senderemail#gmail.com"
#$cc = "ccemail#gmail.com"
# Below subject line will have todays date and Build status as Succeed or Failed
$subject = "$(get-date -format dd-mm-yy) Automation Test report $(Agent.JobStatus)"
$body = "Your email body text"
# Enter the path of existing Archieve output folder
$attachment = "$(Build.ArtifactStagingDirectory)/YourZipFolderName.zip"
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.IsBodyHTML = $true
$message.body = $body
$message.to.add($to)
#$message.cc.add($cc)
$message.from = $username
$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent successfully using GMAIL"
Please make sure to Use run option as "Even if a previous task has failed, unless the build was canceled" as shown below.
You can use Send Email task to achieve it. Details as below:
In the end of your release environment -> Add a Send Email task -> configure required options.
To delivery the artifact files by the Send Email task, you can select the Add Attachment option and specify absolute path for the attachment:

Sorting, automatically adding an attachment to an email, and forwarding an email

What I am hoping to do is once a new email hits a folder containing a specific subject. That email is then forwarded to another inbox and a specific file is automatically attached. The code I have been able to cobble together so far is this. Is a .Net method the appropriate method to achieve my goal or would using Send-MailMessge to a hastable be better method? I am new to PowerShell code I am able to get both methods to work. But was wondering A. which method is preferred. B. is there a better/more efficient way?
#####Define Variables########
$fromaddress = "donotreply#fromemail.com"
$toaddress = "blah#toemail.com"
$bccaddress = "blah#bcc.com"
$CCaddress = "blah#cc.com"
$Subject = "ACtion Required"
$body = get-content .\content.htm
$attachment = "C:\sendemail\test.txt"
$smtpserver = "smtp.labtest.com"
##############################
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.CC.Add($CCaddress)
$message.Bcc.Add($bccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
(Example of the hashtable method
$emailHashSplat = #{ To = $toAddress
From = $fromAddress
Subject = $emailSubject
Body = $emailBody SMTPServer = $smtpServer BodyAsHtml =
$true Attachments = "C:\sendemail\test.txt" # Attachments =)
Stick with Powershell commands whenever possible, .NET might be faster in some cases but it is a best practice to use only Powershell commands when possible.
Also make sure your code is easy to read and understand by others, using hastables with splatting wil help with this, see the following example: Github Gist Link (Click Me!)
Copy of the code, in case of link failure.
### Script Global Settings
#Declare SMTP Connection Settings
$SMTPConnection = #{
#Use Office365, Gmail, Other or OnPremise SMTP Relay FQDN
SmtpServer = 'outlook.office365.com'
#OnPrem SMTP Relay usually uses port 25 without SSL
#Other Public SMTP Relays usually use SSL with a specific port such as 587 or 443
Port = 587
UseSsl = $true
#Option A: Query for Credential at run time.
Credential = Get-Credential -Message 'Enter SMTP Login' -UserName "emailaddress#domain.tld"
<#
#Option B: Hardcoded Credential based on a SecureString
Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList #(
#The SMTP User Emailaddress
"emailaddress#domain.tld"
#The Password as SecureString encoded by the user that wil run this script!
#To create a SecureString Use the folowing Command: Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString
"Enter the SecureString here as a single line" | ConvertTo-SecureString
)
#>
}
### Script Variables
#Declare Mailmessages.
$MailMessageA = #{
From = "emailaddress#domain.tld"
To = #(
"emailaddress#domain.tld"
)
#Cc = #(
# "emailaddress#domain.tld"
#)
#Bcc = #(
# "emailaddress#domain.tld"
#)
Subject = 'Mailmessage from script'
#Priority = 'Normal' #Normal by default, options: High, Low, Normal
#Attachments = #(
#'FilePath'
#)
#InlineAttachments = #{
#'CIDA'='FilePath'
#} #For more information about inline attachments in mailmessages see: https://gallery.technet.microsoft.com/scriptcenter/Send-MailMessage-3a920a6d
BodyAsHtml = $true
Body = "Something Unexpected Occured as no Content has been Provided for this Mail Message!" #Default Message
}
### Script Start
#Retrieve Powershell Version Information and store it as HTML with Special CSS Class
$PSVersionTable_HTLM = ($PSVersionTable.Values | ConvertTo-Html -Fragment) -replace '<table>', '<table class="table">'
#Retrieve CSS Stylesheet
$CSS = Invoke-WebRequest "https://raw.githubusercontent.com/advancedrei/BootstrapForEmail/master/Stylesheet/bootstrap-email.min.css" | Select-Object -ExpandProperty Content
#Build HTML Mail Message and Apply it to the MailMessage HashTable
$MailMessageA.Body = ConvertTo-Html -Title $MailMessageA.Subject -Head "<style>$($CSS)</style>" -Body "
<p>
Hello World,
</p>
<p>
If your recieved this message then this script works.</br>
</br>
<div class='alert alert-info' role='alert'>
Powershell version
</div>
$($PSVersionTable_HTLM)
</P>
" | Out-String
#Send MailMessage
#This example uses the HashTable's with a technique called Splatting to match/bind the Key's in the HashTable with the Parameters of the command.
#Use the # Symbol instead of $ to invoke Splatting, Splatting improves readability and allows for better management and reuse of variables
Send-MailMessage #SMTPConnection #MailMessageA

Having problems reading in data from file and using it on the fly using PowerShell

I am trying to create a PowerShell script that will send an email if a service goes into a stopped state. I would like to be able to read the email configuration from another file.
Email configuration file:
.\emailconfig.conf
$emailSmtpServer = "smtp.company.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "usera"
$emailSmtpPass = "passwordb"
$emailFrom = "userA#company.com"
$emailTo = "userB#company.com"
$emailcc= "userC#company.com"
And this is what I have so far in the PowerShell script:
.\emailservicecheck.ps1
$A = Get-Service "Service B"
if ($A.Status -eq "Stopped") {
Get-Content emailconfig.conf | Out-String
$emailMessage = New-Object System.Net.Mail.MailMessage($emailFrom, $emailTo)
$emailMessage.Cc.Add($emailcc)
$emailMessage.Subject = "subject"
#$emailMessage.IsBodyHtml = $true # true or false depends
$emailMessage.Body = Get-Service "Service B" | Out-String
$SMTPClient = New-Object System.Net.Mail.SmtpClient($emailSmtpServer, $emailSmtpServerPort)
$SMTPClient.EnableSsl = $False
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($emailSmtpUser, $emailSmtpPass);
$SMTPClient.Send($emailMessage)
}
The script works if I enter the text from the email config file into the script but I cannot seem to be able to read in the data from the file on the fly and get the script to work. It errors out and says that my variables are empty.
What you are searching for, (I think) are .psd1 files. I personally prefer them (along with JSON) over the other configuration formats. The link I'm referring to also describes other well-known formats and how to use them in PowerShell.
In short, module manifests work as follows:
configuration.psd1
#{
SmtpServer = "";
MailFrom = "";
Auth = #{
User = "";
Pass = "";
};
}
Script.ps1
$mailConfig = Import-LocalizedData -BaseDirectory C:\ -FileName configuration.psd1
$emailMessage = New-Object System.Net.Mail.MailMessage( $$mailConfig.mailFrom , $mailConfig.mailTo )
As Mark already pointed out, Get-Content emailconfig.conf | Out-String will just output the content of the file, it won't define the variables in your code. For that you'd need to dot-source the file, which requires a file with the extension ".ps1".
If you want to stick with a simple config file format I'd recommend changing the file to something like this:
emailSmtpServer = smtp.company.com
emailSmtpServerPort = 587
emailSmtpUser = usera
emailSmtpPass = passwordb
emailFrom = userA#company.com
emailTo = userB#company.com
emailcc = userC#company.com
And importing it into a hashtable via ConvertFrom-StringData:
$cfg = Get-Content emailconfig.conf | Out-String | ConvertFrom-StringData
The data in the hashtable can be accessed via dot-notation ($cfg.emailFrom) as well as via the index operator ($cfg['emailFrom']), so your code would have to look somewhat like this:
$msg = New-Object Net.Mail.MailMessage($cfg.emailFrom, $cfg.emailTo)
$msg.Cc.Add($cfg.emailcc)
$msg.Subject = 'subject'
$msg.Body = Get-Service 'Service B' | Out-String
$smtp = New-Object Net.Mail.SmtpClient($cfg.emailSmtpServer, $cfg.emailSmtpServerPort)
$smtp.EnableSsl = $false
$smtp.Credentials = New-Object Net.NetworkCredential($cfg.emailSmtpUser, $cfg.emailSmtpPass)
$smtp.Send($msg)
It looks like what you're trying to do is include some script from another file. This can be done by dot sourcing, however the file needs to be saved as a .ps1 file, you can't use .conf.
You'd do it as follows (in place of your existing Get-Content) line:
. .\emailconfig.ps1
Assuming the file is kept in the current working directory of the script.
Your script wasn't working because
get-content emailconfig.conf | Out-String
Was returning the contents of that file to the output pipeline, rather than including it in the script and executing it.
I'm not sure i understood correctly what you want.
If you want to use variables from external file, you need to dot source your external script, for example, create a file named variables.ps1 and put in the same folder
In the beginning of the main script use
. .\variables.ps1
If you are after expanding variables that are in external file to ues as an email template please do as following:
$HTMLBody = get-content "yourfilepath" | Foreach-Object {$ExecutionContext.InvokeCommand.ExpandString($_)}
This will expand all variables and put it in the $HTMLBody variable
Then use:
$emailMessage.Body = (ConvertTo-Html -body $HTMLBody)

Send mail trough TELNET over OVH with .batch script

I would like to use TELNET to send an email with the content of log.txt using one of my OVH mail accounts (noreply#clement.business hosted on OVH) to a gmail address. Due to my society security politics I am not able to install anything on the servers but the OS itself.
So I tried with both batch and PowerShell but without success, I even tried manually, I can telnet OVH but then don't know how to login.
Here's a few things I tried :
$subject = $args[0]
# Create from/to addresses
$from = New-Object system.net.mail.MailAddress "noreply#clement.business"
$to = New-Object system.net.mail.MailAddress "random#gmail.com"
# Create Message
$message = new-object system.net.mail.MailMessage $from, $to
$message.Subject = $subject
$message.Body = #"
Am I even suppose to write here
"#
# Set SMTP Server and create SMTP Client
$server = "I have no idea how to OVH here"
$client = new-object system.net.mail.smtpclient $server... Server what, POP3 ?
# Do
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
try {
$client.Send($message)
}
catch {
"Exception caught in CreateTestMessage: {0}" -f $Error.ToString()
}
I cannot figure that out, it is such a struggle to deal with...
PS : I did use the OVH guide about POP3/SMTP setup, but did not work, or I have no idea what I am doing. Useful link here as well.
Just so you know the difference: POP3 is used to receive email, SMTP is used to send email. You can't use them interchangeably.
A quick google for 'ovh smtp server' shows that the ovh help pages list the SMTP servers as:
Server name: ns0.ovh.net
Port of the outgoing server: 587
Username: identical to the email address
Password: your password for your account, as defined in the creation of the email address
I can't test these as I don't have an ovh account.
I would use Send-MailMessage to send the email as it's much easier to use than your solution:'
This will send an email with the file log.txt as an attachment:
$username = "noreply#clement.business"
$password = "passwordforemailaddress" | ConvertTo-SecureString
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
$parms = #{
From = "noreply#clement.business"
To = "email#gmail.com"
Attachment = "C:\folder\log.txt"
Subject = "Daily Logs"
Body = "Your body text here"
SMTPServer = "ns0.ovh.net"
SMTPPort = "587"
Credential = $credentials
}
Send-MailMessage #params
And these params this will use log.txt as the email body text:
$parms = #{
From = "noreply#clement.business"
To = "email#gmail.com"
Body = Get-Content "C:\folder\log.txt"
Subject = "Daily Logs"
SMTPServer = "ns0.ovh.net"
SMTPPort = "587"
Credential = $credentials
}

How to send Email from a Batch file?

I want the Email and Message in the Code to be sent to my Email "example#gmail.com'. I'm new to coding. Please help me to do this.
#echo off
color a
title Message Me
echo Instructions:
echo 1) Type the message and hit ENTER/RETURN
cd "C:\MessageMe"
set /p user=Email ID:
set /p message=Message:
echo Username="%user%" Message="%message%">Sent_Items.txt
echo Press any key to continue
pause >n
echo Loading.....
echo Enter E-Mail Again
set /p user=Email ID:
echo Username="%user%">Confirmed.txt
echo.
echo Press any key to Send
echo.
echo.
pause >
echo.
echo Processing...
echo.
echo.
echo.
echo.
echo.
pause >n
To send Emails from the Windows command-line, you can
...forget using raw telnet.exe as it cannot accept input from a file
...use a telnet.exe replacement like Albert Yale's telnet scripting tool
...use an actual command-line Email client like blat
...use PowerShell, like e.g. this1:
$EmailFrom = “yourgmailadress#gmail.com”
$EmailTo = “destination#somedomain.com”
$Subject = “The subject of your email”
$Body = “What do you want your email to say”
$SMTPServer = “smtp.gmail.com”
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“usr”, “pass”);
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)