Send email: Difference between revisions

27,081 bytes added ,  1 month ago
Added FreeBASIC
(→‎{{header|Perl 6}}: Add code to actually (theoretically) send the email)
(Added FreeBASIC)
 
(15 intermediate revisions by 7 users not shown)
Line 15:
=={{header|Ada}}==
{{libheader|AWS}}
<langsyntaxhighlight Adalang="ada">with AWS.SMTP, AWS.SMTP.Client, AWS.SMTP.Authentication.Plain;
with Ada.Text_IO;
use Ada, AWS;
Line 42:
end if;
end Sendmail;
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com%2Fforum%2Ftopic39797.html discussion]
{{libheader | COM.ahk}}
<langsyntaxhighlight lang="autohotkey">sSubject:= "greeting"
sText := "hello"
sFrom := "ahk@rosettacode"
Line 83:
COM_Release(pmsg)
COM_Term()
#Include COM.ahk</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SOCKLIB"
Server$ = "smtp.gmail.com"
Line 171:
WHILE FN_readlinesocket(skt%, 10, reply$) > 0 : ENDWHILE
ENDPROC
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Sends mail via the GMail SMTP server, requires [https://curl.haxx.se/libcurl/ libcurl]
{{libheader|libcurl}}
<syntaxhighlight lang="c">
<lang C>
 
#include <curl/curl.h>
Line 275:
return (int)res;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
{{works with|Mono|1.2}}
{{works with|Visual C sharp|Visual C#|2003}}
<syntaxhighlight lang="csharp">
static void Main(string[] args)
{
//First of all construct the SMTP client
 
SmtpClient SMTP = new SmtpClient("smtp.gmail.com", 587); //I have provided the URI and port for GMail, replace with your providers SMTP details
SMTP.EnableSsl = true; //Required for gmail, may not for your provider, if your provider does not require it then use false.
SMTP.DeliveryMethod = SmtpDeliveryMethod.Network;
SMTP.Credentials = new NetworkCredential("YourUserName", "YourPassword");
MailMessage Mail = new MailMessage("yourEmail@address.com", "theirEmail@address.com");
 
 
//Then we construct the message
 
Mail.Subject = "Important Message";
Mail.Body = "Hello over there"; //The body contains the string for your email
//using "Mail.IsBodyHtml = true;" you can put an HTML page in your message body
 
//Then we use the SMTP client to send the message
 
SMTP.Send(Mail);
 
Console.WriteLine("Message Sent");
}
</syntaxhighlight>
 
=={{header|C++}}==
Line 282 ⟶ 311:
{{works with|POCO|1.3.6}}
 
<langsyntaxhighlight lang="cpp">// on Ubuntu: sudo apt-get install libpoco-dev
// or see http://pocoproject.org/
// compile with: g++ -Wall -O3 send-mail-cxx.C -lPocoNet -lPocoFoundation
Line 327 ⟶ 356:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
When run literally as above, should print:
Line 336 ⟶ 365:
 
This version does not do authentication. However, the login() method can accept a username and password for authentication. Also, newer versions of POCO provide SecureSMTPClientSession, for doing STARTTLS.
 
=={{header|C sharp|C#}}==
{{works with|Mono|1.2}}
{{works with|Visual C sharp|Visual C#|2003}}
<lang csharp>
static void Main(string[] args)
{
//First of all construct the SMTP client
 
SmtpClient SMTP = new SmtpClient("smtp.gmail.com", 587); //I have provided the URI and port for GMail, replace with your providers SMTP details
SMTP.EnableSsl = true; //Required for gmail, may not for your provider, if your provider does not require it then use false.
SMTP.DeliveryMethod = SmtpDeliveryMethod.Network;
SMTP.Credentials = new NetworkCredential("YourUserName", "YourPassword");
MailMessage Mail = new MailMessage("yourEmail@address.com", "theirEmail@address.com");
 
 
//Then we construct the message
 
Mail.Subject = "Important Message";
Mail.Body = "Hello over there"; //The body contains the string for your email
//using "Mail.IsBodyHtml = true;" you can put an HTML page in your message body
 
//Then we use the SMTP client to send the message
 
SMTP.Send(Mail);
 
Console.WriteLine("Message Sent");
}
</lang>
 
=={{header|Clojure}}==
Line 370:
 
[https://github.com/drewr/postal Postal] wraps JavaMail to make sending emails simple and platform independent.
<langsyntaxhighlight lang="clojure">(require '[postal.core :refer [send-message]])
 
(send-message {:host "smtp.gmail.com"
Line 380:
:cc ["bob@builder.com" "dora@explorer.com"]
:subject "Yo"
:body "Testing."})</langsyntaxhighlight>
 
{{out}}
Line 387:
=={{header|D}}==
Requires the libcurl library to be installed on the system.
<langsyntaxhighlight lang="d">void main() {
import std.net.curl;
 
Line 396:
s.message = "Subject:test\n\nExample Message";
s.perform;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
procedure SendEmail;
var
Line 433:
end;
end;
</syntaxhighlight>
</lang>
 
=={{header|Diego}}==
This <code>instruct</code>ion instructs a thing in the mist to send an email. It understands that the found <code>thing</code> will have email knowledge (similar to libraries in other languages). If the caller does not have email knowledge, the callee will train the caller on first request. It is at the discretion of the callee to adjust, delay or not send the email.
<syntaxhighlight lang="diego">begin_instruct(Send email)_param({str} from, to, cc, subject, msg, {html}, htmlmsg)_opt({cred}, login)_ns(rosettacode);
set_thread(linger);
find_thing()_first()_email()
? with_found()_label(emailer);
: exit_instruct[]_err(Sorry, no one can send emails!);
;
with_[emailer]_format(html)
? with_[emailer]_cred[login]_email[htmlmsg]_from[from]_to[to]_cc[cc]_subject[subject];
: exit_instruct[]_err(Something went wrong with the email);
: with_[emailer]_cred[login]_email[msg]_from[from]_to[to]_cc[cc]_subject[subject];
: exit_instruct[]_err(Something went wrong with the email);
;
reset_thread();
end_instruct[];
 
set_namespace(rosettacode);
 
// Set up credentials
add_var({cred}, mycred)_server(esvr1)_username(bob)_password(p@$$w0rd); // Other credentials can be added here
 
// Send email:
exec_instruct(Send email)_param()
_from(bob@bobmail.com.invalid) // It is at the discretion of the caller to use this from address
_to(fred@bobmail.com.invalid)
_cc(jill@bobmail.com.invalid)
_subject(Rosettacode wants me to send an email!)
_msg(This is the body of my email.)
_htmlmsg(<b>This is the body of my email, in bold</b>)
_login[mycred]
_me();
 
reset_namespace();</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
Line 439 ⟶ 474:
Variable <code>send-mail-function</code> holds a function for sending a message from the current buffer. The user or sysadmin is expected to set that variable to a preferred method (<code>sendmail</code>, SMTP, etc). The default queries the user for initial setup.
 
<langsyntaxhighlight Lisplang="lisp">(defun my-send-email (from to cc subject text)
(with-temp-buffer
(insert "From: " from "\n"
Line 451 ⟶ 486:
(my-send-email "from@example.com" "to@example.com" ""
"very important"
"body\ntext\n")</langsyntaxhighlight>
 
The buffer filling here pays no attention to charset or possible special characters in the fields or text.
Line 460 ⟶ 495:
This one uses the build-in SMTP vocabulary. Note that 'to' and 'cc' need to be arrays of strings containing an email address.
 
<syntaxhighlight lang="factor">
<lang Factor>
USING: accessors io.sockets locals namespaces smtp ;
IN: scratchpad
Line 468 ⟶ 503:
"my.gmail.address@gmail.com" "qwertyuiasdfghjk" <plain-auth>
>>auth \ smtp-config set-global <email> f >>from t >>to
c >>cc s >>subject b >>body send-email ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
There's a built-in Email library, which will work on the JVM, CLR and Javascript runtimes. Errors are thrown if there is a problem with the protocol or the network.
 
<langsyntaxhighlight lang="fantom">
using email
 
Line 507 ⟶ 541:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
Line 513 ⟶ 547:
Using Outlook COM server. Before compiling the program, it's necessary to use the '''[https://software.intel.com/en-us/node/535422 Intel Fortran Module Wizard]''' from the Visual Studio editor, to generate a Fortran module for the Microsoft Outlook Object Library. The following program has to be linked with this module (msoutl).
 
<langsyntaxhighlight lang="fortran">program sendmail
use ifcom
use msoutl
Line 528 ⟶ 562:
call $Application_Quit(app, status)
call comuninitialize()
end program</langsyntaxhighlight>
 
=={{header|GoFreeBASIC}}==
===FB: LINUX===
Unfortunately, FreeBASIC does not have a built-in library for sending emails. However, you can use an external program such as <code>sendmail</code> or <code>mailx</code> that can be invoked from FreeBASIC using the <code>SHELL</code> function.
 
<syntaxhighlight lang="vbnet">Sub SendEmail(fromAddress As String, toAddress As String, ccAddress As String, _
subject As String, messageText As String, serverName As String, loginDetails As String)
Dim As String comando
comando = "echo '" & messageText & "' | mailx -s '" & subject & "' -r '" _
& fromAddress & "' -S smtp='" & serverName _
& "' -S smtp-auth=login -S smtp-auth-user='" & loginDetails _
& "' -S smtp-auth-password='yourpassword' -c '" & ccAddress & "' '" _
& toAddress & "'"
Shell comando
End Sub
 
Dim As String fromAddress = "your_mail@gmail.com"
Dim As String toAddress = "recipient@gmail.com"
Dim As String ccAddress = "cc@gmail.com"
Dim As String subject = "Mail subject"
Dim As String messageText = "This is the body of the email."
Dim As String serverName = "smtp.gmail.com"
Dim As String loginDetails = "your_username"
</syntaxhighlight>
 
And then call this script from FreeBASIC using the <code>SHELL</code> function:
<syntaxhighlight lang="vbnet">
SendEmail(fromAddress, toAddress, ccAddress, subject, messageText, serverName, loginDetails)
</syntaxhighlight>
 
===FB: WINDOWS===
FreeBASIC does not have a built-in library for interacting with Outlook.
An alternative is to write a script in VBA or VBScript to send email through Outlook, and then call that script from FreeBASIC.
 
<syntaxhighlight lang="vbnet">'VBScript code:
Function EnviarCorreo()
With CreateObject("CDO.Message")
.Subject = "Mail subject"
.From = "your_mail@domain.com"
.To = "recipient@domain.com"
.TextBody = "This is the body of the email."
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"smtp.dominio.com"
.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Configuration.Fields.Update
.Send
End With
End Function</syntaxhighlight>
 
<syntaxhighlight lang="vbnet">'VBA code:
Sub EnviarCorreo()
Dim OutlookApp As Object
Dim OutlookMail As Object
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
With OutlookMail
.To = "recipient@domain.com"
.Subject = "Mail subject"
.Body = "This is the body of the email."
.Send
End With
Set OutlookMail = Nothing
Set OutlookApp = Nothing
End Sub</syntaxhighlight>
 
And then call this script from FreeBASIC using the <code>SHELL</code> function:
<syntaxhighlight lang="vbnet">
Shell "cscript send_mail.vbs"
</syntaxhighlight>
 
=={{header|Go}}==
A full little command-line program that can be used to send simple e-mails. Uses the built-in smtp package.
Supports TLS connections.
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 695 ⟶ 805:
 
fmt.Printf("Message sent.\n")
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
From [http://www.jedox.com/en/send-email-using-javamail-groovy-script/] we can get email solution for Groovy
<syntaxhighlight lang="groovy">
<lang Groovy>
import javax.mail.*
import javax.mail.internet.*
Line 747 ⟶ 857:
/*Call function */
simpleMail(s1, s2 , s3, "TITLE", "TEXT");
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
Line 753 ⟶ 863:
Example using [https://hackage.haskell.org/package/smtp-mail <tt>smtp-mail</tt>] package:
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
 
module Main (main) where
Line 776 ⟶ 886:
[ plainTextPart "This is plain text."
, htmlPart "<h1>Title</h1><p>This is HTML.</p>"
]</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
 
A Unicon-specific solution is:
<langsyntaxhighlight lang="unicon">procedure main(args)
mail := open("mailto:"||args[1], "m", "Subject : "||args[2],
"X-Note: automatically send by Unicon") |
Line 787 ⟶ 897:
every write(mail , !&input)
close (mail)
end</langsyntaxhighlight>
 
=={{header|Java}}==
 
<langsyntaxhighlight lang="java5">import java.util.Properties;
 
import javax.mail.MessagingException;
Line 846 ⟶ 956:
Transport.send(message);
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
using SMTPClient
 
Line 868 ⟶ 978:
sendemail("to@example.com", "from@example.com", "TEST", "hello there test message text here", "smtps://smtp.gmail.com",
user="from@example.com", password="example.com")
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
To compile and run this program 'javax.mail.jar' will need to be present on your system and added to your classpath. Also if you're using the Google SMTP Server then, as well as requiring a gmail account, you'll probably need to temporarily turn on 'access for less secure apps' to prevent it from being blocked.
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
import java.util.Properties
Line 922 ⟶ 1,032:
val password = "secret"
sendEmail(user, tos, ccs, title, body, password)
}</langsyntaxhighlight>
 
=={{header|Lasso}}==
This example leverages Lasso's built in Email_Send method.
 
<langsyntaxhighlight Lassolang="lasso">// with a lot of unneeded params.
// sends plain text and html in same email
// simple usage is below
Line 960 ⟶ 1,070:
-body = 'Lasso is awesome, you should try it!'
)
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
This program requires sendemail.exe and sendemail.pl in the same directory, available free from Caspian's SendEmail Site.
<syntaxhighlight lang="lb">
<lang lb>
text$ = "This is a simple text message."
 
Line 990 ⟶ 1,100:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
Lingo has no built-in support for sending email. But this can be achieved e.g. by using Shell Xtra and one of the available command-line SMTP clients.
{{libheader|Shell Xtra}}
<langsyntaxhighlight lang="lingo">----------------------------------------
-- Sends email via SMTP using senditquiet.exe (15 KB)
-- @param {string} fromAddr
Line 1,047 ⟶ 1,157:
res = sx.shell_cmd(cmd)
return not(res contains "ERROR")
end</langsyntaxhighlight>
 
=={{header|LiveCode}}==
LiveCode provides a built-in method that will create an email in the registered mailto: handler on supported OS.
<langsyntaxhighlight LiveCodelang="livecode">revMail "help@example.com",,"Help!",field "Message"</langsyntaxhighlight>
To create and ''send'' an email in LiveCode requires coding your own smtp client, or using one of a couple of 3rd party stacks.
 
=={{header|LotusScript}}==
 
<langsyntaxhighlight Lotusscriptlang="lotusscript">Dim session As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Line 1,064 ⟶ 1,174:
doc.SendTo = "John Doe"
doc.Subject = "Subject of this mail"
Call doc.Send( False )</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 1,070 ⟶ 1,180:
Using [http://w3.impa.br/~diego/software/luasocket/smtp.html LuaSocket's SMTP module] (from the documentation on that page):
 
<langsyntaxhighlight Lualang="lua">-- load the smtp support
local smtp = require("socket.smtp")
 
Line 1,101 ⟶ 1,211:
source = smtp.message(mesgt)
}
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica has the built-in function SendMail, example:
<langsyntaxhighlight Mathematicalang="mathematica">SendMail["From" -> "from@email.com", "To" -> "to@email.com",
"Subject" -> "Sending Email from Mathematica", "Body" -> "Hello world!",
"Server" -> "smtp.email.com"]</langsyntaxhighlight>
The following options can be specified:
<syntaxhighlight lang="mathematica">"To"
<lang Mathematica>"To"
"Cc"
"Bcc"
Line 1,123 ⟶ 1,233:
"ReplyTo"
"ServerAuthentication"
"UserName"</langsyntaxhighlight>
Possible options for EncryptionProtocol are: "SSL","StartTLS" and "TLS". This function should work fine on all the OS's Mathematica runs, which includes the largest 3: Windows, Linux, Mac OSX.
 
 
=={{header|NewLISP}}==
* using library smtp.lsp
<langsyntaxhighlight NewLISPlang="newlisp">(module "smtp.lsp")
(SMTP:send-mail "user@asite.com" "somebody@isp.com" "Greetings" "How are you today? - john doe -" "smtp.asite.com" "user" "password")</langsyntaxhighlight>
 
=={{header|Nim}}==
Compile with <code>nim c -d:ssl mail</code>
<syntaxhighlight lang ="nim">import smtp, net
 
proc sendMail(fromAddr: string; toAddrs, ccAddrs: seq[string];
subject, message, login, password: string;
server = "smtp.gmail.com"; port = Port 465; ssl = true) =
varlet msg = createMessage(subject, message, toAddrs, ccAddrs)
varlet ssession = connectnewSmtp(server,useSsl port,= ssl, debug = true)
session.connect(server, port)
s.auth(login, password)
session.auth(login, password)
s.sendmail(fromAddr, toAddrs, $msg)
session.sendMail(fromAddr, toAddrs, $msg)
 
sendMail(fromAddr = "nim@gmail.com",
Line 1,150 ⟶ 1,260:
message = "Nim says hi!\nAnd bye again!",
login = "nim@gmail.com",
password = "XXXXXX")</langsyntaxhighlight>
 
=={{header|OCaml}}==
* using the library [http://www.linux-nantes.org/~fmonnier/OCaml/smtp-mail/ smtp-mail-0.1.3]
<langsyntaxhighlight lang="ocaml">let h = Smtp.connect "smtp.gmail.fr";;
Smtp.helo h "hostname";;
Smtp.mail h "<john.smith@example.com>";;
Line 1,164 ⟶ 1,274:
let email_msg = "Happy Birthday";;
Smtp.data h (email_header ^ "\r\n\r\n" ^ email_msg);;
Smtp.quit h;;</langsyntaxhighlight>
 
=={{header|Perl}}==
===Using Net::SMTP===
This subroutine throws an appropriate error if it fails to connect to the server or authenticate. It should work on any platform Perl does.
 
<langsyntaxhighlight lang="perl">use Net::SMTP;
use Authen::SASL;
# Net::SMTP's 'auth' method needs Authen::SASL to work, but
Line 1,176 ⟶ 1,287:
# Authen::SASL here.
 
sub send_email {
{ my %o =
(from => '', to => [], cc => [],
subject => '', body => '',
Line 1,184 ⟶ 1,295:
ref $o{$_} or $o{$_} = [$o{$_}] foreach 'to', 'cc';
 
my $smtp = new Net::SMTP->new($o{host} ? $o{host} : ())
or die "Couldn't connect to SMTP server";
 
Line 1,201 ⟶ 1,312:
$smtp->dataend;
 
return 1;}</lang>
}</syntaxhighlight>
 
An example call:
 
<langsyntaxhighlight lang="perl">send_email
from => 'A. T. Tappman',
to => ['suchandsuch@example.com', 'soandso@example.org'],
Line 1,213 ⟶ 1,325:
host => 'smtp.example.com:587',
user => 'tappman@example.com',
password => 'yossarian';</langsyntaxhighlight>
 
If the <code>host</code> parameter is omitted, <code>send_email</code> falls back on the <code>SMTP_Hosts</code> defined in <code>Net::Config</code>. Hence, only two arguments are strictly necessary:
 
<langsyntaxhighlight lang="perl">send_email
to => 'suchandsuch@example.com',
user => 'tappman@example.com';</langsyntaxhighlight>
 
{{libheader|LWP}}
 
===Using LWP===
LWP can send email by a POST to a <code>mailto:</code> URL. The message is given as a HTTP request. This is mainly of interest for treating different types of URLs in a common way. LWP sends merely by running the <code>sendmail</code> program, or on MacOS classic by SMTP (to <code>SMTPHOSTS</code> environment variable). For reference, the <code>$ua-&gt;post()</code> method does not suit since it constructs a message as MIME "form data".
 
<langsyntaxhighlight lang="perl">use strict;
use LWP::UserAgent;
use HTTP::Request;
Line 1,246 ⟶ 1,357:
send_email('from-me@example.com', 'to-foo@example.com', '',
"very important subject",
"Body text\n");</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
{{libheader|Phix/libcurl}}
<lang perl6>use Email::Simple;
{{trans|C}}
 
Obviously, USER/PWD/URL/etc. would all need altering for your details.
my $to = 'mail@example.com';
For gmail, make sure you enable https://myaccount.google.com/lesssecureapps
my $from = 'me@example.com';
<!--<syntaxhighlight lang="phix">(notonline)-->
my $subject = 'test';
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (libcurl)</span>
my $body = 'This is a test.';
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">libcurl</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
 
my $email = Email::Simple.create(
<span style="color: #008080;">constant</span> <span style="color: #000000;">USER</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"you@gmail.com"</span><span style="color: #0000FF;">,</span>
:header[['To', $to], ['From', $from], ['Subject', $subject]],
<span style="color: #000000;">PWD</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"secret"</span><span style="color: #0000FF;">,</span>
:body($body)
<span style="color: #000000;">URL</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"smtps://smtp.gmail.com:465"</span><span style="color: #0000FF;">,</span>
);
<span style="color: #000000;">FROM</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"sender@gmail.com"</span><span style="color: #0000FF;">,</span>
 
<span style="color: #000000;">TO</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"addressee@email.com"</span><span style="color: #0000FF;">,</span>
say ~$email;
<span style="color: #000000;">CC</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"info@example.org"</span><span style="color: #0000FF;">,</span>
 
<span style="color: #000000;">FMT</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Date: Mon, 13 Jun 2018 11:30:00 +0100\r\n"</span><span style="color: #0000FF;">&</span>
# Note that the following will fail without an actual smtp server that
<span style="color: #008000;">"To: %s\r\n"</span><span style="color: #0000FF;">&</span>
# will accept anonymous emails on port 25 (Not very common anymore).
<span style="color: #008000;">"From: %s (Example User)\r\n"</span><span style="color: #0000FF;">&</span>
# Most public email servers now require authentication and encryption.
<span style="color: #008000;">"Cc: %s (Another example User)\r\n"</span><span style="color: #0000FF;">&</span>
 
<span style="color: #008000;">"Subject: Sanding mail via Phix\r\n"</span><span style="color: #0000FF;">&</span>
my $smtp-server = 'smtp.example.com';
<span style="color: #008000;">"\r\n"</span><span style="color: #0000FF;">&</span>
my $smtp-port = 25;
<span style="color: #008000;">"This mail is being sent by a Phix program.\r\n"</span><span style="color: #0000FF;">&</span>
 
<span style="color: #008000;">"\r\n"</span><span style="color: #0000FF;">&</span>
await IO::Socket::Async.connect($smtp-server, $smtp-port).then(
<span style="color: #008000;">"It connects to the GMail SMTP server, by far the most popular mail program of all.\r\n"</span><span style="color: #0000FF;">&</span>
-> $smtp {
<span style="color: #008000;">"Which is, however, probably not written in Phix.\r\n"</span>
if $smtp.status {
given $smtp.result {
<span style="color: #008080;">function</span> <span style="color: #000000;">read_callback</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">pbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">size</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">nmemb</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">pUserData</span><span style="color: #0000FF;">)</span>
react {
<span style="color: #000080;font-style:italic;">-- copy a maximum of size*nmemb bytes into pbuffer</span>
whenever .Supply() -> $response {
<span style="color: #008080;">if</span> <span style="color: #000000;">size</span><span style="color: #0000FF;">==</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">nmemb</span><span style="color: #0000FF;">==</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">size</span><span style="color: #0000FF;">*</span><span style="color: #000000;">nmemb</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if $response ~~ /^220/ {
<span style="color: #0000FF;">{</span><span style="color: #004080;">integer</span> <span style="color: #000000;">sent</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">len</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">pPayload</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">peekns</span><span style="color: #0000FF;">({</span><span style="color: #000000;">pUserData</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">})</span>
.print( join "\r\n",
<span style="color: #004080;">integer</span> <span style="color: #000000;">bytes_written</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">size</span><span style="color: #0000FF;">*</span><span style="color: #000000;">nmemb</span><span style="color: #0000FF;">,</span><span style="color: #000000;">len</span><span style="color: #0000FF;">-</span><span style="color: #000000;">sent</span><span style="color: #0000FF;">)</span>
"EHLO $smtp-server",
<span style="color: #7060A8;">mem_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pbuffer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pPayload</span><span style="color: #0000FF;">+</span><span style="color: #000000;">sent</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bytes_written</span><span style="color: #0000FF;">)</span>
"MAIL FROM:<{$email.from}>",
<span style="color: #000000;">sent</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">bytes_written</span>
"RCPT TO:<{$email.to}>",
<span style="color: #7060A8;">pokeN</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pUserData</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sent</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">machine_word</span><span style="color: #0000FF;">())</span>
"DATA", $email.body,
<span style="color: #008080;">return</span> <span style="color: #000000;">bytes_written</span>
'.', ''
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
)
<span style="color: #008080;">constant</span> <span style="color: #000000;">read_cb</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">call_back</span><span style="color: #0000FF;">({</span><span style="color: #008000;">'+'</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"read_callback"</span><span style="color: #0000FF;">)})</span>
}
elsif $response ~~ /^250/ {
<span style="color: #008080;">constant</span> <span style="color: #004080;">string</span> <span style="color: #000000;">payload_text</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">FMT</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">TO</span><span style="color: #0000FF;">,</span><span style="color: #000000;">FROM</span><span style="color: #0000FF;">,</span><span style="color: #000000;">CC</span><span style="color: #0000FF;">})</span>
.print("QUIT\r\n");
done
<span style="color: #7060A8;">curl_global_init</span><span style="color: #0000FF;">()</span>
}
<span style="color: #004080;">CURLcode</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">CURLE_OK</span>
else {
<span style="color: #004080;">atom</span> <span style="color: #000000;">slist_recipients</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">NULL</span>
say "Send email failed with: $response";
<span style="color: #004080;">atom</span> <span style="color: #000000;">curl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">curl_easy_init</span><span style="color: #0000FF;">()</span>
done
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_USERNAME</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">USER</span><span style="color: #0000FF;">)</span>
}
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_PASSWORD</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">PWD</span><span style="color: #0000FF;">)</span>
}
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_URL</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">URL</span><span style="color: #0000FF;">)</span>
.close
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_USE_SSL</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLUSESSL_ALL</span><span style="color: #0000FF;">)</span>
}
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_SSL_VERIFYPEER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
}
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_SSL_VERIFYHOST</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
}
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_MAIL_FROM</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">FROM</span><span style="color: #0000FF;">)</span>
}
<span style="color: #000000;">slist_recipients</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">curl_slist_append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">slist_recipients</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">TO</span><span style="color: #0000FF;">)</span>
)</lang>
<span style="color: #000000;">slist_recipients</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">curl_slist_append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">slist_recipients</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">CC</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_MAIL_RCPT</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">slist_recipients</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_READFUNCTION</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">read_cb</span><span style="color: #0000FF;">);</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">pUserData</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">allocate</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">machine_word</span><span style="color: #0000FF;">()*</span><span style="color: #000000;">3</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">pPayload</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">allocate_string</span><span style="color: #0000FF;">(</span><span style="color: #000000;">payload_text</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">pokeN</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pUserData</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">payload_text</span><span style="color: #0000FF;">),</span><span style="color: #000000;">pPayload</span><span style="color: #0000FF;">},</span><span style="color: #7060A8;">machine_word</span><span style="color: #0000FF;">())</span>
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_READDATA</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pUserData</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_UPLOAD</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--curl_easy_setopt(curl, CURLOPT_VERBOSE, true)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">curl_easy_perform</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">!=</span><span style="color: #004600;">CURLE_OK</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"curl_easy_perform() failed: %d (%s)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">curl_easy_strerror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">curl_slist_free_all</span><span style="color: #0000FF;">(</span><span style="color: #000000;">slist_recipients</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">curl_easy_cleanup</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">curl_global_cleanup</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">mail('hello@world.net', 'My Subject', "A Message!", "From: my@address.com");</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
PicoLisp has a built-in '[http://software-lab.de/doc/refM.html#mail mail]'
function. A minimal call would be
<langsyntaxhighlight PicoLisplang="picolisp">(mail "localhost" 25 "me@from.org" "you@to.org" "Subject" NIL "Hello")</langsyntaxhighlight>
Instead of "Hello" an arbitrary number of arguments may follow (possibly
containing executable expressions) for the message body.
Line 1,316 ⟶ 1,444:
Untested:
 
<langsyntaxhighlight lang="pike">int main(){
string to = "some@email.add";
string subject = "Hello There.";
Line 1,323 ⟶ 1,451:
Protocols.SMTP.Client()->simple_mail(to,subject,from,msg);
}</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Line 1,329 ⟶ 1,457:
 
The parameters are splatted with a hashtable:
<syntaxhighlight lang="powershell">
<lang PowerShell>
[hashtable]$mailMessage = @{
From = "weirdBoy@gmail.com"
Line 1,344 ⟶ 1,472:
 
Send-MailMessage @mailMessage
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight Purebasiclang="purebasic">InitNetwork()
 
CreateMail(0, "from@mydomain.com", "This is the Subject")
Line 1,361 ⟶ 1,489:
Else
MessageRequester("Error", "Can't sent the mail !")
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,369 ⟶ 1,497:
Tested on Windows, it should work on all [[wp:POSIX|POSIX]] platforms.
 
<langsyntaxhighlight lang="python">import smtplib
 
def sendemail(from_addr, to_addr_list, cc_addr_list,
Line 1,386 ⟶ 1,514:
problems = server.sendmail(from_addr, to_addr_list, message)
server.quit()
return problems</langsyntaxhighlight>
 
Example use:
<langsyntaxhighlight lang="python">sendemail(from_addr = 'python@RC.net',
to_addr_list = ['RC@gmail.com'],
cc_addr_list = ['RC@xx.co.uk'],
Line 1,395 ⟶ 1,523:
message = 'Howdy from a python function',
login = 'pythonuser',
password = 'XXXXX')</langsyntaxhighlight>
 
{{out|Sample Email received}}
Line 1,411 ⟶ 1,539:
Using Outlook COM server with the Pywin32 library.
 
<langsyntaxhighlight lang="python">import win32com.client
 
def sendmail(to, title, body):
Line 1,423 ⟶ 1,551:
ol.Quit()
 
sendmail("somebody@somewhere", "Title", "Hello")</langsyntaxhighlight>
 
=={{header|R}}==
Line 1,431 ⟶ 1,559:
Using Outlook COM server with the '''[http://www.omegahat.net/RDCOMClient/ RDCOMClient]''' package.
 
<langsyntaxhighlight lang="r">library(RDCOMClient)
 
send.mail <- function(to, title, body) {
Line 1,444 ⟶ 1,572:
}
 
send.mail("somebody@somewhere", "Title", "Hello")</langsyntaxhighlight>
 
=={{header|Racket}}==
 
Racket has a built-in library for sending e-mails:
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,474 ⟶ 1,602:
"Subject")
'("Hello World!"))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>use Email::Simple;
 
my $to = 'mail@example.com';
my $from = 'me@example.com';
my $subject = 'test';
my $body = 'This is a test.';
 
my $email = Email::Simple.create(
:header[['To', $to], ['From', $from], ['Subject', $subject]],
:body($body)
);
 
say ~$email;
 
# Note that the following will fail without an actual smtp server that
# will accept anonymous emails on port 25 (Not very common anymore).
# Most public email servers now require authentication and encryption.
 
my $smtp-server = 'smtp.example.com';
my $smtp-port = 25;
 
await IO::Socket::Async.connect($smtp-server, $smtp-port).then(
-> $smtp {
if $smtp.status {
given $smtp.result {
react {
whenever .Supply() -> $response {
if $response ~~ /^220/ {
.print( join "\r\n",
"EHLO $smtp-server",
"MAIL FROM:<{$email.from}>",
"RCPT TO:<{$email.to}>",
"DATA", $email.body,
'.', ''
)
}
elsif $response ~~ /^250/ {
.print("QUIT\r\n");
done
}
else {
say "Send email failed with: $response";
done
}
}
.close
}
}
}
}
)</syntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">send user@host.dom "My message"</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,483 ⟶ 1,665:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
See "Send email..." + nl
Line 1,500 ⟶ 1,682:
CalmoSoft")
see "Done.." + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,514 ⟶ 1,696:
Uses the {{libheader|RubyGems}} gems [http://tmail.rubyforge.org TMail] which allows us to manipulate email objects conveniently, and [http://mime-types.rubyforge.org/ mime-types] which guesses a file's mime type based on its filename.
 
<langsyntaxhighlight lang="ruby">require 'base64'
require 'net/smtp'
require 'tmail'
Line 1,590 ⟶ 1,772:
:password => 'secret'
}
)</langsyntaxhighlight>
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">filename msg email
to="afriend@someserver.com"
cc="anotherfriend@somecompany.com"
Line 1,602 ⟶ 1,784:
file msg;
put "Hello, Connected World!";
run;</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import java.util.Properties
 
import javax.mail.internet.{ InternetAddress, MimeMessage }
Line 1,639 ⟶ 1,821:
Transport.send(message)
}
}</langsyntaxhighlight>
 
=={{header|SQL PL}}==
Line 1,645 ⟶ 1,827:
With SQL PL:
You must first set the SMTP server in the database from which you want to send the message.
<langsyntaxhighlight lang="sql pl">
UPDATE DB CFG FOR myDb USING SMTP_SERVER 'smtp.ibm.com';
 
CALL UTL_MAIL.SEND ('senderAccount@myDomain.com','recipientAccount@yourDomain.com', 'copy@anotherDomain.com', NULL, 'The subject of the message', 'The content of the message');
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,664 ⟶ 1,846:
{{tcllib|mime}}{{tcllib|smtp}}
Also may use the [http://tls.sourceforge.net/ tls] package (needed for sending via gmail).
<langsyntaxhighlight lang="tcl">package require smtp
package require mime
package require tls
Line 1,686 ⟶ 1,868:
}
 
send_simple_message recipient@example.com "Testing" "This is a test message."</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
works only with Windows, on Linux OS it is possible to send an email by using the Execute function
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
 
Line 1,705 ⟶ 1,887:
 
ENDIF
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
<langsyntaxhighlight lang="txr">#!/usr/bin/txr
@(next :args)
@(cases)
Line 1,730 ⟶ 1,912:
@(end)
.
@(end)</langsyntaxhighlight>
 
{{out}}
Line 1,751 ⟶ 1,933:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
Const olMailItem = 0
 
Line 1,769 ⟶ 1,951:
Sub Test()
SendMail "somebody@somewhere", "Title", "Hello"
End Sub</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function send_mail(from,recipient,cc,subject,message)
With CreateObject("CDO.Message")
Line 1,793 ⟶ 1,975:
 
Call send_mail("Alerts@alerts.org","jkspeed@jkspeed.org","","Test Email","this is a test message")
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|WrenGo}}
An embedded application with a Go host so we can use their net/smtp module.
<syntaxhighlight lang="wren">/* Send_email.wren */
 
foreign class Authority {
construct plainAuth(identity, username, password, host) {}
}
 
class SMTP {
foreign static sendMail(address, auth, from, to, msg)
}
 
class Message {
static check(host, user, pass) {
if (host == "") Fiber.abort("Bad host")
if (user == "") Fiber.abort("Bad username")
if (pass == "") Fiber.abort("Bad password")
}
 
construct new(from, to, cc, subject, content) {
_from = from
_to = to
_cc = cc
_subject = subject
_content = content
}
 
toString {
var to = _to.join(",")
var cc = _cc.join(",")
var s1 = "From: " + _from + "\n"
var s2 = "To: " + to + "\n"
var s3 = "Cc: " + cc + "\n"
var s4 = "Subject: " + _subject + "\n\n"
return s1 + s2 + s3 + s4 + _content
}
 
send(host, port, user, pass) {
Message.check(host, user, pass)
SMTP.sendMail(
"%(host):%(port)",
Authority.plainAuth("", user, pass, host),
_from,
_to,
toString
)
}
}
 
foreign class Reader {
construct new() {}
 
foreign readString(delim)
}
 
var host = "smtp.gmail.com"
var port = 587
var user = "some.user@gmail.com"
var pass = "secret"
 
var bufin = Reader.new()
var NL = 10
 
System.write("From: ")
var from = bufin.readString(NL).trim()
 
var to = []
while (true) {
System.write("To (Blank to finish): ")
var tmp = bufin.readString(NL).trim()
if (tmp == "") break
to.add(tmp)
}
 
var cc = []
while (true) {
System.write("Cc (Blank to finish): ")
var tmp = bufin.readString(NL).trim()
if (tmp == "") break
cc.add(tmp)
}
 
System.write("Subject: ")
var subject = bufin.readString(NL).trim()
 
var contentLines = []
while (true) {
System.write("Content line (Blank to finish): ")
var line = bufin.readString(NL).trim()
if (line == "") break
contentLines.add(line)
}
var content = contentLines.join("\r\n")
 
var m = Message.new(from, to, cc, subject, content)
System.print("\nSending message...")
m.send(host, port, user, pass)
System.print("Message sent.")</syntaxhighlight>
<br>
We now embed this script in the following Go program and run it.
<syntaxhighlight lang="go">/* go run Send_email.go */
 
package main
 
import(
wren "github.com/crazyinfin8/WrenGo"
"log"
"bufio"
"net/smtp"
"os"
)
 
type any = interface{}
 
func sendMail(vm *wren.VM, parameters []any) (any, error) {
address := parameters[1].(string)
handle := parameters[2].(*wren.ForeignHandle)
ifc, _ := handle.Get()
auth := ifc.(*smtp.Auth)
from := parameters[3].(string)
handle2 := parameters[4].(*wren.ListHandle)
le, _ := handle2.Count()
to := make([]string, le)
for i := 0; i < le; i++ {
ifc2, _ := handle2.Get(i)
to[i] = ifc2.(string)
}
msg := parameters[5].(string)
err := smtp.SendMail(address, *auth, from, to, []byte(msg))
if err != nil {
log.Fatal(err)
}
return nil, nil
}
 
func plainAuth(vm *wren.VM, parameters []any) (any, error) {
identity := parameters[1].(string)
username := parameters[2].(string)
password := parameters[3].(string)
host := parameters[4].(string)
auth := smtp.PlainAuth(identity, username, password, host)
return &auth, nil
}
 
func newReader(vm *wren.VM, parameters []any) (any, error) {
reader := bufio.NewReader(os.Stdin)
return &reader, nil
}
 
func readString(vm *wren.VM, parameters []any) (any, error) {
handle := parameters[0].(*wren.ForeignHandle)
ifc, _ := handle.Get()
bufin := ifc.(**bufio.Reader)
delim := byte(parameters[1].(float64))
s, _ := (*bufin).ReadString(delim)
return s, nil
}
 
func main() {
vm := wren.NewVM()
fileName := "Send_email.wren"
 
smtpMethodMap := wren.MethodMap { "static sendMail(_,_,_,_,_)": sendMail }
readerMethodMap := wren.MethodMap { "readString(_)": readString }
 
classMap := wren.ClassMap {
"Authority": wren.NewClass(plainAuth, nil, nil),
"SMTP" : wren.NewClass(nil, nil, smtpMethodMap),
"Reader" : wren.NewClass(newReader, nil, readerMethodMap),
}
 
module := wren.NewModule(classMap)
vm.SetModule(fileName, module)
vm.InterpretFile(fileName)
vm.Free()
}</syntaxhighlight>
2,122

edits