Issues with newline while using blat - windows

I have to send a mail via BLAT. We are shifting from Postie to BLAT. The send mail refuses to send the mail via a batch file.
My code goes as follows
REM ########### Initialize BLAT SMTP Server and User Name #######################
ECHO.
%V_EMAIL_PATH%\blat.exe -install %V_HOST% "mno#xyz.com"
ECHO.
REM ------------------------ Send Email Notifications ---------------
#ECHO ON
set V_EMAIL_ID="abcd#xyz.com"
set V_SUBJ="Test mail to a group"
set V_MSG="Hello|test mail to prevent failure during delivery while sending automated mails|Thanks|mno"
GOTO Sendemail
:Sendemail
%V_EMAIL_PATH%\blat.exe -body %V_MSG% -to "%V_EMAIL_ID%" -from "mno#xyz.com" -subject "Test Mail"
The error being thrown is as follows
D:\pmserver\pm-work\Utilities\blat.exe -body "Hello test mail to prevent failure during delivery while sending automated mails. Thanks RM Primary" -to "abcd#xyz.com" -from "mno#xyz.com" -subject "Test Mail"
Blat v2.2.2 (build : Feb 26 2004 10:37:13)
Blat saw and processed these options, and was confused by the last one...
Hello|test mail to prevent failure during delivery while sending automated mails.|Thanks|mno
Do not understand argument: Hello|test mail to prevent failure during delivery while sending automated mails|Thanks|mno
I tried using breakline as well but even that is failing.
reekar V

try this:
#echo OFF &SETLOCAL
set "V_EMAIL_ID=abcd#xyz.com"
set "V_SUBJ=Test mail to a group"
set "V_MSG=Hello|test mail to prevent failure during delivery while sending automated mails|Thanks|mno"
%V_EMAIL_PATH%\blat -body "%V_MSG%" -to "%V_EMAIL_ID%" -from "mno#xyz.com" -subject "Test Mail"

Related

Email a batch variable to myself using batch script [duplicate]

I'm running Windows 2003 Service Pack 2. I have a batch file that runs on demand. I want to have an email sent every time the batch file runs. The email is simple, just a sentence indicating that the batch file ran; it is the same every time.
I've tried a couple of things to get this done. I thought of telnet, but I can't figure out how to redirect a set of commands into telnet; Windows batch files don't have a Unix-style "here document," and calling "telnet <scriptfile" where scriptfile contains the commands to send an email didn't work. I also found a couple of solutions on the internet using CDO.Message, but I've never used that before and I kept getting error messages that I don't understand.
How can I send a simple email from a Windows batch file?
Max is on he right track with the suggestion to use Windows Scripting for a way to do it without installing any additional executables on the machine. His code will work if you have the IIS SMTP service setup to forward outbound email using the "smart host" setting, or the machine also happens to be running Microsoft Exchange. Otherwise if this is not configured, you will find your emails just piling up in the message queue folder (\inetpub\mailroot\queue). So, unless you can configure this service, you also want to be able to specify the email server you want to use to send the message with. To do that, you can do something like this in your windows script file:
Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "your#address.com"
objMail.To = "destination#address.com"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing
I've used Blat ( http://www.blat.net/ ) for many years.
It's a simple command line utility that can send email from command line.
It's free and opensource.
You can use command like "Blat myfile.txt -to fee#fi.com -server smtp.domain.com -port 6000"
Here is some other software you can try to send email from command line (I've never used them):
http://caspian.dotconf.net/menu/Software/SendEmail/
http://www.petri.co.il/sendmail.htm
http://www.petri.co.il/software/mailsend105.zip
http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm
Here ( http://www.petri.co.il/send_mail_from_script.htm ) you can find other various way of sending email from a VBS script, plus link to some of the mentioned software
The following VBScript code is taken from that page
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "me#mydomain.com"
objEmail.To = "you#yourdomain.com"
objEmail.Subject = "Server is down!"
objEmail.Textbody = "Server100 is no longer accessible over the network."
objEmail.Send
Save the file as something.vbs
Set Msg = CreateObject("CDO.Message")
With Msg
.To = "you#yourdomain.com"
.From = "me#mydomain.com"
.Subject = "Hello"
.TextBody = "Just wanted to say hi."
.Send
End With
Save the file as something2.vbs
I think these VBS scripts use the windows default mail server, if present.
I've not tested these scripts...
If PowerShell is available, the Send-MailMessage commandlet is a single one-line command that could easily be called from a batch file to handle email notifications. Below is a sample of the line you would include in your batch file to call the PowerShell script (the %xVariable% is a variable you might want to pass from your batch file to the PowerShell script):
--[BATCH FILE]--
:: ...your code here...
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -command C:\MyScripts\EmailScript.ps1 %xVariable%
Below is an example of what you might include in your PowerShell script (you must include the PARAM line as the first non-remark line in your script if you included passing the %xVariable% from your batch file:
--[POWERSHELL SCRIPT]--
Param([String]$xVariable)
# ...your code here...
$smtp = "smtp.[emaildomain].com"
$to = "[Send to email address]"
$from = "[From email address]"
$subject = "[Subject]"
$body = "[Text you want to include----the <br> is a line feed: <br> <br>]"
$body += "[This could be a second line of text]" + "<br> "
$attachment="[file name if you would like to include an attachment]"
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Attachment $attachment -Priority high
If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.
I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.
A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.
$emailSmtpServerPort = "587"
$emailSmtpUser = "username"
$emailSmtpPass = 'password'
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[From email address]"
$emailMessage.To.Add( "[Send to email address]" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = #"
<p>Here is a message that is <strong>HTML formatted</strong>.</p>
<p>From your friendly neighborhood IT guy</p>
"#
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
It works for me, by using double quotes around variables.
I am using batch script to call powershell Send-MailMessage
Batch Script:send_email.bat
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command 'E:\path\send_email.ps1
Pwershell Script send_email.ps1
Send-MailMessage -From "noreply#$env:computername" -To '<target_email#example.com>' -Subject 'Blah Blah' -SmtpServer 'smtp.domain.com' -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "
I struggled with the same problem and finally found a simple soultion. I know I am late to answer this question. But still writing if it can help someone like me who is searching for it.
You can send simple mail using Powershell script. Make sure to connect this in your bat file
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "hi#company.com"
$Mail.Subject = "hello"
$Mail.Body ="Hello. I am here to wish you"
$Mail.Send()
Using this, you need not use any other party apps or install anything extra. It just needs Outlook. I hope that will be already there in many office accounts.
This post helped me
Send E-Mail using powershell

Windows Batch - Getting Error when trying to send mail via blat.exe

I have a simple batch-script, where at the end I want to send an automated e-mail by calling the function blat.exe:
blat.exe -body "Das ist ein Test von Admin" -s "ABCDEFGH" -attacht "\\server\C\applic\abcd\tool\output\datafile.txt" -f mail#adress.com -t mail#adress.com
I am getting the following error:
C:\C\applic\abcd\tool>blat.exe -body "Das ist ein Test von Admin" -s "ABCDEFGH" -attacht "\\server\C\applic\abcd\tool\output\datafile.txt" -f mail#adress.com -t mail#adress.com
-body does not exist
I cannot figure out why it isn't working. Can anyone help here?

How to send a simple email from a Windows batch file?

I'm running Windows 2003 Service Pack 2. I have a batch file that runs on demand. I want to have an email sent every time the batch file runs. The email is simple, just a sentence indicating that the batch file ran; it is the same every time.
I've tried a couple of things to get this done. I thought of telnet, but I can't figure out how to redirect a set of commands into telnet; Windows batch files don't have a Unix-style "here document," and calling "telnet <scriptfile" where scriptfile contains the commands to send an email didn't work. I also found a couple of solutions on the internet using CDO.Message, but I've never used that before and I kept getting error messages that I don't understand.
How can I send a simple email from a Windows batch file?
Max is on he right track with the suggestion to use Windows Scripting for a way to do it without installing any additional executables on the machine. His code will work if you have the IIS SMTP service setup to forward outbound email using the "smart host" setting, or the machine also happens to be running Microsoft Exchange. Otherwise if this is not configured, you will find your emails just piling up in the message queue folder (\inetpub\mailroot\queue). So, unless you can configure this service, you also want to be able to specify the email server you want to use to send the message with. To do that, you can do something like this in your windows script file:
Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "your#address.com"
objMail.To = "destination#address.com"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing
I've used Blat ( http://www.blat.net/ ) for many years.
It's a simple command line utility that can send email from command line.
It's free and opensource.
You can use command like "Blat myfile.txt -to fee#fi.com -server smtp.domain.com -port 6000"
Here is some other software you can try to send email from command line (I've never used them):
http://caspian.dotconf.net/menu/Software/SendEmail/
http://www.petri.co.il/sendmail.htm
http://www.petri.co.il/software/mailsend105.zip
http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm
Here ( http://www.petri.co.il/send_mail_from_script.htm ) you can find other various way of sending email from a VBS script, plus link to some of the mentioned software
The following VBScript code is taken from that page
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "me#mydomain.com"
objEmail.To = "you#yourdomain.com"
objEmail.Subject = "Server is down!"
objEmail.Textbody = "Server100 is no longer accessible over the network."
objEmail.Send
Save the file as something.vbs
Set Msg = CreateObject("CDO.Message")
With Msg
.To = "you#yourdomain.com"
.From = "me#mydomain.com"
.Subject = "Hello"
.TextBody = "Just wanted to say hi."
.Send
End With
Save the file as something2.vbs
I think these VBS scripts use the windows default mail server, if present.
I've not tested these scripts...
If PowerShell is available, the Send-MailMessage commandlet is a single one-line command that could easily be called from a batch file to handle email notifications. Below is a sample of the line you would include in your batch file to call the PowerShell script (the %xVariable% is a variable you might want to pass from your batch file to the PowerShell script):
--[BATCH FILE]--
:: ...your code here...
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -command C:\MyScripts\EmailScript.ps1 %xVariable%
Below is an example of what you might include in your PowerShell script (you must include the PARAM line as the first non-remark line in your script if you included passing the %xVariable% from your batch file:
--[POWERSHELL SCRIPT]--
Param([String]$xVariable)
# ...your code here...
$smtp = "smtp.[emaildomain].com"
$to = "[Send to email address]"
$from = "[From email address]"
$subject = "[Subject]"
$body = "[Text you want to include----the <br> is a line feed: <br> <br>]"
$body += "[This could be a second line of text]" + "<br> "
$attachment="[file name if you would like to include an attachment]"
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Attachment $attachment -Priority high
If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.
I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.
A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.
$emailSmtpServerPort = "587"
$emailSmtpUser = "username"
$emailSmtpPass = 'password'
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[From email address]"
$emailMessage.To.Add( "[Send to email address]" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = #"
<p>Here is a message that is <strong>HTML formatted</strong>.</p>
<p>From your friendly neighborhood IT guy</p>
"#
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
It works for me, by using double quotes around variables.
I am using batch script to call powershell Send-MailMessage
Batch Script:send_email.bat
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command 'E:\path\send_email.ps1
Pwershell Script send_email.ps1
Send-MailMessage -From "noreply#$env:computername" -To '<target_email#example.com>' -Subject 'Blah Blah' -SmtpServer 'smtp.domain.com' -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "
I struggled with the same problem and finally found a simple soultion. I know I am late to answer this question. But still writing if it can help someone like me who is searching for it.
You can send simple mail using Powershell script. Make sure to connect this in your bat file
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "hi#company.com"
$Mail.Subject = "hello"
$Mail.Body ="Hello. I am here to wish you"
$Mail.Send()
Using this, you need not use any other party apps or install anything extra. It just needs Outlook. I hope that will be already there in many office accounts.
This post helped me
Send E-Mail using powershell

Sending mail from a Bash shell script

I am writing a Bash shell script for Mac that sends an email notification by opening an automator application that sends email out with the default mail account in Mail.app. The automator application also attaches a text file that the script has written to. The problems with this solution are
It is visible in the GUI when sending
It steals focus if Mail is not the current application
It is dependent on Mail.app's account setup being valid in the future
I figure to get around those shortcomings I should send the mail directly from the script by entering SMTP settings, address to send to, etc. directly in the script. The catch is I would like to deploy this script on multiple computers (10.5 and 10.6) without enabling Postfix on the computer. Is it possible to do this in the script so it will run on a base Mac OS X install of 10.5. and 10.6?
Update: I've found the -bs option for Sendmail which seems to be what I need, but I'm at a loss of how to specify settings.
Also, to clarify, the reason I'd like to specify SMTP settings is that mails from localhost on port 25 sent out via Postfix would be blocked by most corporate firewalls, but if I specify the server and an alternate port I won't run into that problem.
Since Mac OS X includes Python, consider using a Python script instead of a Bash script. I haven't tested the sending portion, but it follows the standard example.
Python script
# Settings
SMTP_SERVER = 'mail.myisp.com'
SMTP_PORT = 25
SMTP_USERNAME = 'myusername'
SMTP_PASSWORD = '$uper$ecret'
SMTP_FROM = 'sender#example.com'
SMTP_TO = 'recipient#example.com'
TEXT_FILENAME = '/script/output/my_attachment.txt'
MESSAGE = """This is the message
to be sent to the client.
"""
# Now construct the message
import smtplib, email
from email import encoders
import os
msg = email.MIMEMultipart.MIMEMultipart()
body = email.MIMEText.MIMEText(MESSAGE)
attachment = email.MIMEBase.MIMEBase('text', 'plain')
attachment.set_payload(open(TEXT_FILENAME).read())
attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(TEXT_FILENAME))
encoders.encode_base64(attachment)
msg.attach(body)
msg.attach(attachment)
msg.add_header('From', SMTP_FROM)
msg.add_header('To', SMTP_TO)
# Now send the message
mailer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
# EDIT: mailer is already connected
# mailer.connect()
mailer.login(SMTP_USERNAME, SMTP_PASSWORD)
mailer.sendmail(SMTP_FROM, [SMTP_TO], msg.as_string())
mailer.close()
I hope this helps.
Actually, "mail" works just as well.
mail -s "subject line" name#address.ext < filename
works perfectly fine, as long as you have SMTP set up on your machine. I think that most Macs do, by default.
If you don't have SMTP, then the only thing you're going to be able to do is go through Mail.app. An ALTERNATIVE way to go through mail.app is via AppleScript. When you tell Mail.app to send mail via AppleScript you can tell it to not pop up any windows... (this does still require Mail.app to be configured).
Introduction to Scripting Mail has a good description of how to work with mail in AppleScript.
There is a program called Sendmail.
You probably don't want to use the -bs command unless you are sending it as raw SMTP like Martin's example. -bs is for running an SMTP server as a deamon. Sendmail will send directly to the receiving mail server (on port 25) unless you override it in the configuration file. You can specify the configuration file by the -C paramter.
In the configuration, you can specify a relay server (any mail server or sendmail running -bs on another machine)
Using a properly configured relay server is good idea because when IT manages mail servers they implement SPF and domain keys. That keeps your mail out of the junk bin.
If port 25 is blocked you are left with two options.
Use the corporate SMTP server.
Run sendmail -bd on a machine outside of
the corporate firewall that listens
on a port other than 25.
I believe you can add configuration parameters on the command line. What you want is the SMART_HOST option. So call Sendmail like sendmail -OSMART_HOST=nameofhost.com.
Probably the only way you could do this, while keeping the program self-sufficient, is if you have direct access to an SMTP server from the clients.
If you do have direct access to an SMTP server you can use the SMTP example from wikipedia and turn it into something like this:
#!/bin/bash
telnet smtp.example.org 25 <<_EOF
HELO relay.example.org
MAIL FROM:<joe#example.org>
RCPT TO:<jane#example.org>
DATA
From: Joe <joe#example.org>
To: Jane <jane#example.org>
Subject: Hello
Hello, world!
.
QUIT
_EOF
To handle errors I would redirect the output from telnet to a file and then grep that for a "success message" later. I am not sure what format the message should be, but I see something like "250 2.0.0 Ok: queued as D86A226C574" in the output from my SMTP server. This would make me grep for "^250.*queued as".
Send mail from Bash with one line:
echo "your mail body" | mail -s "your subject" yourmail#yourdomain.com -a "From: sender#senderdomain.com"
sendEmail is a script that you can use to send email from the command line using more complicated settings, including connecting to a remote smtp server:
http://caspian.dotconf.net/menu/Software/SendEmail/
On OSX it is easily installable via macports:
http://sendemail.darwinports.com/
Below is the help page for the command, take note of the -s, -xu, -xp flags:
Synopsis: sendEmail -f ADDRESS [options]
Required:
-f ADDRESS from (sender) email address
* At least one recipient required via -t, -cc, or -bcc
* Message body required via -m, STDIN, or -o message-file=FILE
Common:
-t ADDRESS [ADDR ...] to email address(es)
-u SUBJECT message subject
-m MESSAGE message body
-s SERVER[:PORT] smtp mail relay, default is localhost:25
Optional:
-a FILE [FILE ...] file attachment(s)
-cc ADDRESS [ADDR ...] cc email address(es)
-bcc ADDRESS [ADDR ...] bcc email address(es)
Paranormal:
-xu USERNAME authentication user (for SMTP authentication)
-xp PASSWORD authentication password (for SMTP authentication)
-l LOGFILE log to the specified file
-v verbosity, use multiple times for greater effect
-q be quiet (no stdout output)
-o NAME=VALUE see extended help topic "misc" for details
Help:
--help TOPIC The following extended help topics are available:
addressing explain addressing and related options
message explain message body input and related options
misc explain -xu, -xp, and others
networking explain -s, etc
output explain logging and other output options
I whipped this up for the challenge. If you remove the call to 'dig' to obtain the mail relay, it is a 100% native Bash script.
#!/bin/bash
MAIL_FROM="sfinktah#bash.spamtrak.org"
RCPT_TO="sfinktah#bash.spamtrak.org"
MESSAGE=message.txt
SMTP_PORT=25
SMTP_DOMAIN=${RCPT_TO##*#}
index=1
while read PRIORITY RELAY
do
RELAY[$index]=$RELAY
((index++))
done < <( dig +short MX $SMTP_DOMAIN )
RELAY_COUNT=${#RELAY[#]}
SMTP_COMMANDS=( "HELO $HOSTNAME" "MAIL FROM: <$MAIL_FROM>" "RCPT TO: <$RCPT_TO>" "DATA" "." "QUIT" )
SMTP_REPLY=([25]=OK [50]=FAIL [51]=FAIL [52]=FAIL [53]=FAIL [54]=FAIL [55]=FAIL [45]=WAIT [35]=DATA [22]=SENT)
for (( i = 1 ; i < RELAY_COUNT ; i++ ))
do
SMTP_HOST="${RELAY[$i]}"
echo "Trying relay [$i]: $SMTP_HOST..."
exec 5<>/dev/tcp/$SMTP_HOST/$SMTP_PORT
read HELO <&5
echo GOT: $HELO
for COMMAND_ORDER in 0 1 2 3 4 5 6 7
do
OUT=${SMTP_COMMANDS[COMMAND_ORDER]}
echo SENDING: $OUT
echo -e "$OUT\r" >&5
read -r REPLY <&5
echo REPLY: $REPLY
# CODE=($REPLY)
CODE=${REPLY:0:2}
ACTION=${SMTP_REPLY[CODE]}
case $ACTION in
WAIT ) echo Temporarily Fail
break
;;
FAIL ) echo Failed
break
;;
OK ) ;;
SENT ) exit 0
;;
DATA ) echo Sending Message: $MESSAGE
cat $MESSAGE >&5
echo -e "\r" >&5
;;
* ) echo Unknown SMTP code $CODE
exit 2
esac
done
done
Here is a simple Ruby script to do this. Ruby ships on the Mac OS X versions you mentioned.
Replace all the bits marked 'replace'. If it fails, it returns a non-zero exit code and a Ruby back trace.
require 'net/smtp'
SMTPHOST = 'replace.yoursmtpserver.example.com'
FROM = '"Your Email" <youremail#replace.example.com>'
def send(to, subject, message)
body = <<EOF
From: #{FROM}
To: #{to}
Subject: #{subject}
#{message}
EOF
Net::SMTP.start(SMTPHOST) do |smtp|
smtp.send_message body, FROM, to
end
end
send('someemail#replace.example.com', 'testing', 'This is a message!')
You can embed this in a Bash script like so:
ruby << EOF
... script here ...
EOF
For some other ways to send Ruby emails, see Stack Overflow question How do I send mail from a Ruby program?.
You can use other languages that ship with Mac OS X as well:
How do I send email with Perl?
Sending HTML email using Python
1) Why not configure postfix to handle outbound mail only and relay it via a mail gateway? Its biggest advantage is that it is already installed on OS X clients.
2) Install and configure one of the lightweight MTAs that handle only outbound mail, like nullmailer or ssmtp (available via MacPorts).
In both cases use mailx(1) (or mutt if you want to get fancy) to send the mails from a shell script.
There are several questions on Server Fault that go into the details.
sendmail and even postfix may be too big to install if all you want to do is to send a few emails from your scripts.
If you have a Gmail account for example, you can use Google's servers to send email using SMTP. If you don't want to use gGoogle's server, as long as you have access to some SMTP server, it should work.
A very lightweight program that makes it easy to do so is msmtp. They have examples of configuration files in their documentation.
The easiest way to do it would be to set up a system-wide default:
account default
host smtp.gmail.com
from john.doe#gmail.com
user john.doe#gmail.com
password XXX
port 587
msmtp should be very easy to install. In fact, there is a port for it, so it could be as easy as port install msmtp.
After installing and configuring msmtp, you can send email to john.doe#gmail.com using:
mail -s <subject> john.doe#gmail.com <<EOF
<mail text, as many lines as you want. Shell variables will be expanded>.
EOF
You can put the above in a script. See man mail for details.
Here's a modified shells script snip I've used on various UNIX systems...
(echo "${MESSAGE}" | ${uuencode} ${ATTACHMENT}$basename ${ATTACHMENT}) | ${mailx} -s "${SUBJECT}" "${TO_LIST}"
uuencode and mailx are set to the executables. The other variables are from user input parsed using getopts.
This does work but I have to admit more often than not I use a simple Java program to send console emails.
Try mtcmail. Its a fairly complete email sender, completely standalone.

How can I send an email from the command line using blat when the body contains carriage returns and line feeds?

I have a windows server which sends emails to me through a BASIC program. If the message body contains carriage returns/line feeds then the email never finishes. Only the first line is sent to me. I tried replacing them with \n but that didn't help as the email came to me with the \n in it. Any ideas?
Here is the command I'm using:
blat -to mike.roosa#toltsg.com -subject "[DEV] PO Detail Report" -body "Attached file
is ready for import.
From 01/01/09 to 01/29/09
PO Status not egual to 'C'" -attach "C:\TXT\PODetail_26879.csv" -log
C:\EMAIL.LOG\20090129.TXT -timestamp'.
If you want to do it all inline use the '|' character
-body 1st line|second line|third line
You can put the body in a text file and have blat send that:
blat [text file here] -to mike.roosa#toltsg.com -subject "[DEV] PO Detail Report" -attach "C:\TXT\PODetail_26879.csv" -log
C:\EMAIL.LOG\20090129.TXT -timestamp'
Just use Mail Alert Simple Mailer:
https://sourceforge.net/projects/mail-alert/
MailAlert.exe -r address#example.com -b "#Your_Directory\File_with_Mail_Body.txt"
You can also attach HTML file as an email body (remember to change PlaintextOnly=no in such a case).

Resources