Here is a GAWK program of mine that implements outgoing SMTP. While not a one-liner, this is much shorter and less tedious than trying to do it in C.
$ cat /bin/awkmail
#!/bin/gawk -f
BEGIN { smtp="/inet/tcp/0/smtp.yourco.com/25";
ORS="\r\n"; r=ARGV[1]; s=ARGV[2]; sbj=ARGV[3]; # /bin/awkmail to from subj < in
print "helo " ENVIRON["HOSTNAME"] |& smtp;
smtp |& getline j; print j
print "mail from: " s |& smtp; smtp |& getline j; print j
if(match(r, ","))
{
split(r, z, ",")
for(y in z) { print "rcpt to: " z[y] |& smtp; smtp |& getline j; print j }
}
else { print "rcpt to: " r |& smtp; smtp |& getline j; print j }
print "data" |& smtp; smtp |& getline j; print j
print "From: " s |& smtp; ARGV[2] = "" # not a file
print "To: " r |& smtp; ARGV[1] = "" # not a file
if(length(sbj)) { print "Subject: " sbj |& smtp; ARGV[3] = "" } # not a file
print "" |& smtp
while(getline > 0) print |& smtp
print "." |& smtp; smtp |& getline j; print j
print "quit" |& smtp; smtp |& getline j; print j
close(smtp) } # /inet/protocol/local-port/remote-host/remote-port
Re:Understanding Awk
by meltedcapacitor on Thursday September 30, 2021 @02:48PM
(#28709723)
Cheap fix: the space after MAIL FROM: and RCPT TO: is not standard compliant.
That's a beautiful use of the language, it reminds me of some of the awk CGI efforts out there.
For example: https://www.gnu.org/software/gawk/manual/gawkinet/html_node/...
IMHO, that's too big for awk, why not python?
for example:
#!/usr/bin/python
import smtplib
from email.mime.text import MIMEText
msg = 'hi'
subj='read this!'
smtp_server='mail.example.com'
smtp_from='[email protected]'
smtp_to='[email protected]'
m = MIMEText(msg)
m['To'] = smtp_to
m['From'] = smtp_from
m['Subject'] = subj
s = smtplib.SMTP(smtp_server)
s.sendmail(smtp_from, [smtp_to], m.as_string())
s.quit()
of course, you seem to think in gawk so if that works
for you that's what you should continue doing!by the way, I hacked this example from another script which attached a logfile:
with open(arg.logfile) as f:
log_contents = f.read()
m = MIMEText(log_contents)
you can also use: from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
and then: m = MIMEMultipart()
m.attach(MIMEText('\n\n%s\n\n'%xkcd_img_title))
m.attach(MIMEImage(xkcd_img))Your script doesn't even do the same thing. You are importing a library that implements SMTP, which is missing the point.
The AWK script doesn't need libraries, so it can actually be useful in places where you have awk but not Python.
Consider the input
a b
Awk will treat it as having two columns (by default), while cut will treat each space as it’s own column.
Awk is also a little nicer for whitespace; cut makes specifying the delimiter (with say “-d\ “) a little more vexing.
Looking at my command history, I mostly use awk to extract a field like this:
(I know "cut" is supposed to do the same thing, but it was never reliable for me - maybe tabs/spaces?)