Send email

From Rosetta Code
Jump to: navigation, search
Send email
You are encouraged to solve this task according to the task description, using any language you may know.
Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.
  • If appropriate, explain what notifications of problems/success are given.
  • Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.
  • Note how portable the solution given is between operating systems when multi-OS languages are used.

(Remember to obfuscate any sensitive data used in examples)


[edit] Ada

Library: AWS
with AWS.SMTP, AWS.SMTP.Client, AWS.SMTP.Authentication.Plain;
with Ada.Text_IO;
use Ada, AWS;
procedure Sendmail is
Status : SMTP.Status;
Auth : aliased constant SMTP.Authentication.Plain.Credential :=
SMTP.Authentication.Plain.Initialize ("id", "password");
Isp : SMTP.Receiver;
Isp :=
Port => 5025,
Credential => Auth'Unchecked_Access);
From => SMTP.E_Mail ("Me", "[email protected]"),
To => SMTP.E_Mail ("You", "[email protected]"),
Subject => "subject",
Message => "Here is the text",
Status => Status);
if not SMTP.Is_Ok (Status) then
("Can't send message :" & SMTP.Status_Message (Status));
end if;
end Sendmail;

[edit] AutoHotkey

ahk discussion

Library: COM.ahk
sSubject:= "greeting"
sText := "hello"
sFrom := "ahk@rosettacode"
sTo := "whomitmayconcern"
sServer := "" ; specify your SMTP server
nPort := 465 ; 25
bTLS := True ; False
inputbox, sUsername, Username
inputbox, sPassword, password
pmsg := COM_CreateObject("CDO.Message")
pcfg := COM_Invoke(pmsg, "Configuration")
pfld := COM_Invoke(pcfg, "Fields")
COM_Invoke(pfld, "Item", "", 2)
COM_Invoke(pfld, "Item", "", 60)
COM_Invoke(pfld, "Item", "", sServer)
COM_Invoke(pfld, "Item", "", nPort)
COM_Invoke(pfld, "Item", "", bTLS)
COM_Invoke(pfld, "Item", "", 1)
COM_Invoke(pfld, "Item", "", sUsername)
COM_Invoke(pfld, "Item", "", sPassword)
COM_Invoke(pfld, "Update")
COM_Invoke(pmsg, "Subject", sSubject)
COM_Invoke(pmsg, "From", sFrom)
COM_Invoke(pmsg, "To", sTo)
COM_Invoke(pmsg, "TextBody", sText)
COM_Invoke(pmsg, "Send")
#Include COM.ahk

[edit] BBC BASIC

      INSTALL @lib$+"SOCKLIB"
Server$ = ""
From$ = "sender@somewhere"
To$ = "recipient@elsewhere"
CC$ = "another@nowhere"
Subject$ = "Rosetta Code"
Message$ = "This is a test of sending email."
PROCsendmail(Server$, From$, To$, CC$, "", Subject$, "", Message$)
DEF PROCsendmail(smtp$,from$,to$,cc$,bcc$,subject$,replyto$,body$)
LOCAL D%, S%, skt%, reply$
SYS "GetLocalTime", S%
SYS "GetDateFormat", 0, 0, S%, "ddd, dd MMM yyyy ", D%, 18
SYS "GetTimeFormat", 0, 0, S%, "HH:mm:ss +0000", D%+17, 15
D%?31 = 13
skt% = FN_tcpconnect(smtp$,"mail")
IF skt% <= 0 skt% = FN_tcpconnect(smtp$,"25")
IF skt% <= 0 ERROR 100, "Failed to connect to SMTP server"
IF FN_readlinesocket(skt%, 1000, reply$)
WHILE FN_readlinesocket(skt%, 10, reply$) > 0 : ENDWHILE
PROCsend(skt%,"HELO "+FN_gethostname)
PROCmail(skt%,"MAIL FROM: ",from$)
IF to$<>"" PROClist(skt%,to$)
IF cc$<>"" PROClist(skt%,cc$)
IF bcc$<>"" PROClist(skt%,bcc$)
PROCsend(skt%, "DATA")
IF FN_writelinesocket(skt%, "Date: "+$D%)
IF FN_writelinesocket(skt%, "From: "+from$)
IF FN_writelinesocket(skt%, "To: "+to$)
IF cc$<>"" IF FN_writelinesocket(skt%, "Cc: "+cc$)
IF subject$<>"" IF FN_writelinesocket(skt%, "Subject: "+subject$)
IF replyto$<>"" IF FN_writelinesocket(skt%, "Reply-To: "+replyto$)
IF FN_writelinesocket(skt%, "MIME-Version: 1.0")
IF FN_writelinesocket(skt%, "Content-type: text/plain; charset=US-ASCII")
IF FN_writelinesocket(skt%, "")
IF FN_writelinesocket(skt%, body$)
IF FN_writelinesocket(skt%, ".")
DEF PROClist(skt%,list$)
LOCAL comma%
WHILE ASClist$=32 list$=MID$(list$,2):ENDWHILE
comma% = INSTR(list$,",")
IF comma% THEN
PROCmail(skt%,"RCPT TO: ",LEFT$(list$,comma%-1))
list$ = MID$(list$,comma%+1)
PROCmail(skt%,"RCPT TO: ",list$)
UNTIL comma% = 0
DEF PROCmail(skt%,cmd$,mail$)
I% = INSTR(mail$,"<")
J% = INSTR(mail$,">",I%)
PROCsend(skt%, cmd$+MID$(mail$,I%,J%-I%+1))
PROCsend(skt%, cmd$+"<"+mail$+">")
DEF PROCsend(skt%,cmd$)
LOCAL reply$
IF FN_writelinesocket(skt%,cmd$) < 0 THEN ERROR 100, "Send failed"
IF FN_readlinesocket(skt%, 200, reply$)
WHILE FN_readlinesocket(skt%, 10, reply$) > 0 : ENDWHILE

[edit] C++

Library: POCO
Works with: POCO version 1.3.6
// on Ubuntu: sudo apt-get install libpoco-dev
// or see
// compile with: g++ -Wall -O3 send-mail-cxx.C -lPocoNet -lPocoFoundation
#include <cstdlib>
#include <iostream>
#include <Poco/Net/SMTPClientSession.h>
#include <Poco/Net/MailMessage.h>
using namespace Poco::Net;
int main (int argc, char **argv)
MailMessage msg;
msg.addRecipient (MailRecipient (MailRecipient::PRIMARY_RECIPIENT,
"[email protected]",
"Alice Moralis"));
msg.addRecipient (MailRecipient (MailRecipient::CC_RECIPIENT,
"[email protected]",
"Patrick Kilpatrick"));
msg.addRecipient (MailRecipient (MailRecipient::BCC_RECIPIENT,
"[email protected]",
"Michael Carmichael"));
msg.setSender ("Roy Kilroy <[email protected]>");
msg.setSubject ("Rosetta Code");
msg.setContent ("Sending mail from C++ using POCO C++ Libraries");
SMTPClientSession smtp (""); // SMTP server name
smtp.login ();
smtp.sendMessage (msg);
smtp.close ();
std::cerr << "Sent mail successfully!" << std::endl;
catch (std::exception &e)
std::cerr << "failed to send mail: " << e.what() << std::endl;

When run literally as above, should print:

failed to send mail: Host not found

since does not exist. To get it to work, you'll need to fill in the name of an SMTP server (such as the one provided by your ISP), and you should adjust the addresses of the sender and the recipient(s).

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.

[edit] C#

Works with: Mono version 1.2
Works with: Visual C# version 2003
static void Main(string[] args)
//First of all construct the SMTP client
SmtpClient SMTP = new SmtpClient("", 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("[email protected]", "[email protected]");
//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
Console.WriteLine("Message Sent");

[edit] Clojure

Library: postal

Postal wraps JavaMail to make sending emails simple and platform independent.

(require '[postal.core :refer [send-message]])
(send-message {:host ""
 :ssl true
 :user your_username
 :pass your_password}
{:from "[email protected]"
 :to ["[email protected]"]
 :cc ["[email protected]" "[email protected]"]
 :subject "Yo"
 :body "Testing."})
{:error :SUCCESS, :code 0, :message "messages sent"}

[edit] D

Requires the libcurl library to be installed on the system.

void main() {
auto s = SMTP("smtps://");
s.setAuthentication("[email protected]", "somepassword");
s.mailTo = ["<[email protected]>"];
s.mailFrom = "<[email protected]>";
s.message = "Subject:test\n\nExample Message";

[edit] Delphi

procedure SendEmail;
msg: TIdMessage;
smtp: TIdSMTP;
smtp := TIdSMTP.Create;
smtp.Host := '';
smtp.Port := 587;
smtp.Username := 'login';
smtp.Password := 'password';
smtp.AuthType := satNone;
msg := TIdMessage.Create(nil);
with msg.Recipients.Add do begin
Address := '[email protected]';
Name := 'Doug';
with msg.Sender do begin
Address := '[email protected]';
Name := 'Fred';
msg.Subject := 'subj';
msg.Body.Text := 'here goes email message';

[edit] Emacs Lisp

Variable send-mail-function 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 (sendmail, SMTP, etc). The default queries the user for initial setup.

(defun my-send-email (from to cc subject text)
(insert "From: " from "\n"
"To: " to "\n"
"Cc: " cc "\n"
"Subject: " subject "\n"
mail-header-separator "\n"
(funcall send-mail-function)))
(my-send-email "[email protected]" "[email protected]" ""
"very important"

The buffer filling here pays no attention to charset or possible special characters in the fields or text.

(For user-level interactive mailing, compose-mail creates and pre-fills a message buffer ready for the user to edit and send, or not send.)

[edit] Factor

This one uses the build-in SMTP vocabulary. Note that 'to' and 'cc' need to be arrays of strings containing an email address.

USING: kernel accessors smtp io.sockets namespaces ;
IN: learn
: send-mail ( from to cc subject body -- )
"" 587 <inet> smtp-server set
smtp-tls? on
"[email protected]" "password" <plain-auth> smtp-auth set
swap >>from
swap >>to
swap >>cc
swap >>subject
swap >>body
send-email ;

[edit] 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.

using email
class Mail
// create a client for sending email - add your own host/username/password
static SmtpClient makeClient ()
client := SmtpClient
host = "yourhost"
username = "yourusername"
password = "yourpassword"
return client
public static Void main()
// create email
email := Email
to = ["to@addr"]
from = "from@addr"
cc = ["cc@addr"]
subject = test"
body = TextPart { text = "test email" }
// create client and send email
makeClient.send (email)

[edit] 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.

package main
import (
type Message struct {
From string
To []string
Cc []string
Subject string
Content string
func (m Message) Bytes() (r []byte) {
to := strings.Join(m.To, ",")
cc := strings.Join(m.Cc, ",")
r = append(r, []byte("From: "+m.From+"\n")...)
r = append(r, []byte("To: "+to+"\n")...)
r = append(r, []byte("Cc: "+cc+"\n")...)
r = append(r, []byte("Subject: "+m.Subject+"\n\n")...)
r = append(r, []byte(m.Content)...)
func (m Message) Send(host string, port int, user, pass string) (err error) {
err = check(host, user, pass)
if err != nil {
err = smtp.SendMail(fmt.Sprintf("%v:%v", host, port),
smtp.PlainAuth("", user, pass, host),
func check(host, user, pass string) error {
if host == "" {
return errors.New("Bad host")
if user == "" {
return errors.New("Bad username")
if pass == "" {
return errors.New("Bad password")
return nil
func main() {
var flags struct {
host string
port int
user string
pass string
flag.StringVar(&, "host", "", "SMTP server to connect to")
flag.IntVar(&flags.port, "port", 587, "Port to connect to SMTP server on")
flag.StringVar(&flags.user, "user", "", "Username to authenticate with")
flag.StringVar(&flags.pass, "pass", "", "Password to authenticate with")
err := check(, flags.user, flags.pass)
if err != nil {
bufin := bufio.NewReader(os.Stdin)
fmt.Printf("From: ")
from, err := bufin.ReadString('\n')
if err != nil {
fmt.Printf("Error: %v\n", err)
from = strings.Trim(from, " \t\n\r")
var to []string
for {
fmt.Printf("To (Blank to finish): ")
tmp, err := bufin.ReadString('\n')
if err != nil {
fmt.Printf("Error: %v\n", err)
tmp = strings.Trim(tmp, " \t\n\r")
if tmp == "" {
to = append(to, tmp)
var cc []string
for {
fmt.Printf("Cc (Blank to finish): ")
tmp, err := bufin.ReadString('\n')
if err != nil {
fmt.Printf("Error: %v\n", err)
tmp = strings.Trim(tmp, " \t\n\r")
if tmp == "" {
cc = append(cc, tmp)
fmt.Printf("Subject: ")
subject, err := bufin.ReadString('\n')
if err != nil {
fmt.Printf("Error: %v\n", err)
subject = strings.Trim(subject, " \t\n\r")
fmt.Printf("Content (Until EOF):\n")
content, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Printf("Error: %v\n", err)
content = bytes.Trim(content, " \t\n\r")
m := Message{
From: from,
To: to,
Cc: cc,
Subject: subject,
Content: string(content),
fmt.Printf("\nSending message...\n")
err = m.Send(, flags.port, flags.user, flags.pass)
if err != nil {
fmt.Printf("Error: %v\n", err)
fmt.Printf("Message sent.\n")

[edit] Groovy

From [1] we can get email solution for Groovy

import javax.mail.*
import javax.mail.internet.*
public static void simpleMail(String from, String password, String to,
String subject, String body) throws Exception {
String host = "";
Properties props = System.getProperties();
/* is needed in script to avoid error "Could not convert socket to TLS" */
props.setProperty("", host);
props.put("mail.smtp.auth", true);
props.put("", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", "587");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, password);
transport.sendMessage(message, message.getAllRecipients());
/* Set email address sender */
String s1 = "[email protected]";
/* Set password sender */
String s2 = "";
/* Set email address sender */
String s3 = "[email protected]"
/*Call function */
simpleMail(s1, s2 , s3, "TITLE", "TEXT");

[edit] Icon and Unicon

A Unicon-specific solution is:

procedure main(args)
mail := open("mailto:"||args[1], "m", "Subject : "||args[2],
"X-Note: automatically send by Unicon") |
stop("Cannot send mail to ",args[1])
every write(mail , !&input)
close (mail)

[edit] Java

import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
* Mail

public class Mail
* Session

protected Session session;
* Mail constructor.
* @param host Host

public Mail(String host)
Properties properties = new Properties();
properties.put("", host);
session = Session.getDefaultInstance(properties);
* Send email message.
* @param from From
* @param tos Recipients
* @param ccs CC Recipients
* @param subject Subject
* @param text Text
* @throws MessagingException

public void send(String from, String tos[], String ccs[], String subject,
String text)
throws MessagingException
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
for (String to : tos)
message.addRecipient(RecipientType.TO, new InternetAddress(to));
for (String cc : ccs)
message.addRecipient(RecipientType.TO, new InternetAddress(cc));

[edit] Lasso

This example leverages Lasso's built in Email_Send method.

// with a lot of unneeded params.
// sends plain text and html in same email
// simple usage is below
-host = '',
-port = 25,
-timeout = 100,
-username = '',
-password = 'secure_password',
-priority = 'immediate',
-to = '[email protected]',
-cc = '[email protected]',
-bcc = '[email protected]',
-from = '[email protected]',
-replyto = '[email protected]',
-sender = '[email protected]',
-subject = 'Lasso is awesome',
-body = 'Lasso is awesome, you should try it!',
-html = '<p>Lasso is <b>awesome</b>, you should try it!</p>',
-attachments = '/path/to/myFile.txt'
// simple usage
// sends plan text email
-host = '',
-username = '',
-password = 'secure_password',
-to = '[email protected]',
-from = '[email protected]',
-subject = 'Lasso is awesome',
-body = 'Lasso is awesome, you should try it!'

[edit] Liberty BASIC

This program requires sendemail.exe and in the same directory, available free from Caspian's SendEmail Site.

text$ = "This is a simple text message."
from$ = "[email protected]"
username$ = "[email protected]"
'password$ = "***********"
recipient$ = "[email protected]"
server$ = ""
subject$ = chr$( 34) +text$ +chr$( 34) ' Use quotes to allow spaces in text.
message$ = chr$( 34) +"Hello world." +chr$( 34)
attach$ = "a.txt"
logfile$ = "sendemail.log"
cmd$ = " -f "; from$;_ 'from
" -t "; recipient$;_ 'to
" -u "; subject$;_ 'subject
" -s "; server$;_ 'server
" -m "; message$;_ 'message
" -a "; attach$;_ 'file to attach
" -l "; logfile$;_ 'file to log result in
" -xu "; username$ 'smtp user name
'" -xp "; password$ 'smtp password not given so will ask in a CMD window
run "sendEmail.exe "; cmd$, HIDE

[edit] LotusScript

Dim session As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Set db = session.CurrentDatabase
Set doc = New NotesDocument( db )
doc.Form = "Memo"
doc.SendTo = "John Doe"
doc.Subject = "Subject of this mail"
Call doc.Send( False )

[edit] Lua

Using LuaSocket's SMTP module (from the documentation on that page):

-- load the smtp support
local smtp = require("socket.smtp")
-- Connects to server "localhost" and sends a message to users
-- "[email protected]", "[email protected]",
-- and "[email protected]".
-- Note that "fulano" is the primary recipient, "beltrano" receives a
-- carbon copy and neither of them knows that "sicrano" received a blind
-- carbon copy of the message.
from = "<[email protected]>"
rcpt = {
"<[email protected]>",
"<[email protected]>",
"<[email protected]>"
mesgt = {
headers = {
to = "Fulano da Silva <[email protected]>",
cc = '"Beltrano F. Nunes" <[email protected]>',
subject = "My first message"
body = "I hope this works. If it does, I can send you another 1000 copies."
r, e = smtp.send{
from = from,
rcpt = rcpt,
source = smtp.message(mesgt)

[edit] Mathematica

Mathematica has the built-in function SendMail, example:

SendMail["From" -> "[email protected]", "To" -> "[email protected]", 
"Subject" -> "Sending Email from Mathematica", "Body" -> "Hello world!",
"Server" -> ""]

The following options can be specified:


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.

[edit] NewLISP

  • using library smtp.lsp
(module "smtp.lsp") 
(SMTP:send-mail "[email protected]" "[email protected]" "Greetings" "How are you today? - john doe -" "" "user" "password")

[edit] Nim

Compile with nim c -d:ssl mail

import smtp, net
proc sendMail(fromAddr: string; toAddrs, ccAddrs: seq[string];
subject, message, login, password: string;
server = ""; port = Port 465; ssl = true) =
var msg = createMessage(subject, message, toAddrs, ccAddrs)
var s = connect(server, port, ssl, debug = true)
s.auth(login, password)
s.sendmail(fromAddr, toAddrs, $msg)
sendMail(fromAddr = "[email protected]",
toAddrs = @["[email protected]"],
ccAddrs = @[],
subject = "Hi from Nim",
message = "Nim says hi!\nAnd bye again!",
login = "[email protected]",
password = "XXXXXX")

[edit] OCaml

let h = Smtp.connect "";;
Smtp.helo h "hostname";;
Smtp.mail h "<[email protected]>";;
Smtp.rcpt h "<[email protected]>";;
let email_header = "\
From: John Smith <[email protected]>
To: John Doe <[email protected]>
Subject: surprise"
let email_msg = "Happy Birthday";; h (email_header ^ "\r\n\r\n" ^ email_msg);;
Smtp.quit h;;

[edit] Perl

This subroutine throws an appropriate error if it fails to connect to the server or authenticate. It should work on any platform Perl does.

use Net::SMTP;
use Authen::SASL;
# Net::SMTP's 'auth' method needs Authen::SASL to work, but
# this is undocumented, and if you don't have the latter, the
# method will just silently fail. Hence we explicitly use
# Authen::SASL here.
sub send_email
{my %o =
(from => '', to => [], cc => [],
subject => '', body => '',
host => '', user => '', password => '',
ref $o{$_} or $o{$_} = [$o{$_}] foreach 'to', 'cc';
my $smtp = new Net::SMTP($o{host} ? $o{host} : ())
or die "Couldn't connect to SMTP server";
$o{password} and
$smtp->auth($o{user}, $o{password}) ||
die 'SMTP authentication failed';
$smtp->recipient($_) foreach @{$o{to}}, @{$o{cc}};
$o{from} and $smtp->datasend("From: $o{from}\n");
$smtp->datasend('To: ' . join(', ', @{$o{to}}) . "\n");
@{$o{cc}} and $smtp->datasend('Cc: ' . join(', ', @{$o{cc}}) . "\n");
$o{subject} and $smtp->datasend("Subject: $o{subject}\n");
return 1;}

An example call:

from => 'A. T. Tappman',
to => ['[email protected]', '[email protected]'],
cc => '[email protected]',
subject => 'Important message',
body => 'I yearn for you tragically.',
host => '',
user => '[email protected]',
password => 'yossarian';

If the host parameter is omitted, send_email falls back on the SMTP_Hosts defined in Net::Config. Hence, only two arguments are strictly necessary:

to => '[email protected]',
user => '[email protected]';
Library: LWP

LWP can send email by a POST to a mailto: 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 sendmail program, or on MacOS classic by SMTP (to SMTPHOSTS environment variable). For reference, the $ua->post() method does not suit since it constructs a message as MIME "form data".

use strict;
use LWP::UserAgent;
use HTTP::Request;
sub send_email {
my ($from, $to, $cc, $subject, $text) = @_;
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new (POST => "mailto:$to",
[ From => $from,
Cc => $cc,
Subject => $subject ],
my $resp = $ua->request($req);
if (! $resp->is_success) {
print $resp->status_line,"\n";
send_email('[email protected]', '[email protected]', '',
"very important subject",
"Body text\n");

[edit] PHP

mail('[email protected]', 'My Subject', "A Message!", "From: [email protected]");

[edit] PicoLisp

PicoLisp has a built-in 'mail' function. A minimal call would be

(mail "localhost" 25 "[email protected]" "[email protected]" "Subject" NIL "Hello")

Instead of "Hello" an arbitrary number of arguments may follow (possibly containing executable expressions) for the message body.

The 6th argument (here 'NIL') may specify a list of attachments.

[edit] Pike


int main(){
string to = "[email protected]";
string subject = "Hello There.";
string from = "[email protected]";
string msg = "Hello there! :)";

[edit] PureBasic

CreateMail(0, "[email protected]", "This is the Subject")
SetMailBody(0, "Hello " + Chr(10) + "This is a mail !")
AddMailRecipient(0, "[email protected]", #PB_Mail_To)
AddMailRecipient(0, "[email protected]", #PB_Mail_Cc)
If SendMail(0, "")
MessageRequester("Information", "Mail correctly sent !")
MessageRequester("Error", "Can't sent the mail !")

[edit] Python

The function returns a dict of any addresses it could not forward to; other connection problems raise errors.
Tested on Windows, it should work on all POSIX platforms.

import smtplib
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message,
login, password,
header = 'From: %s\n' % from_addr
header += 'To: %s\n' % ','.join(to_addr_list)
header += 'Cc: %s\n' % ','.join(cc_addr_list)
header += 'Subject: %s\n\n' % subject
message = header + message
server = smtplib.SMTP(smtpserver)
problems = server.sendmail(from_addr, to_addr_list, message)
return problems

Example use:

sendemail(from_addr    = '[email protected]', 
to_addr_list = ['[email protected]'],
cc_addr_list = ['[email protected]'],
subject = 'Howdy',
message = 'Howdy from a python function',
login = 'pythonuser',
password = 'XXXXX')
Sample Email received:
Message-ID: <[email protected]>
Date: Tue, 30 Jun 2009 22:04:56 -0700 (PDT)
From: [email protected]
To: [email protected]
Cc: [email protected]
Subject: Howdy

Howdy from a python function

[edit] R

Library: tcltk
Library: gdata
Library: caTools

R does not have a built-in facility for sending emails though some code for this, written by Ben Bolker, is available here.

[edit] Racket

Racket has a built-in library for sending e-mails:

#lang racket
;; using sendmail:
(require net/sendmail)
"[email protected]" "Some Subject"
'("[email protected]" "[email protected]")
'("[email protected]")
'("[email protected]")
(list "Some lines of text" "go here."))
;; and using smtp (and adding more headers here):
(require net/head net/smtp)
"Sender <[email protected]>"
'("Recipient <[email protected]>")
"Sender <[email protected]>"
'("Recipient <[email protected]>")
'() ; CC
'() ; BCC
'("Hello World!"))

[edit] REBOL

send user@host.dom "My message"

[edit] Ruby

Uses the
Library: RubyGems
gems TMail which allows us to manipulate email objects conveniently, and mime-types which guesses a file's mime type based on its filename.
require 'base64'
require 'net/smtp'
require 'tmail'
require 'mime/types'
class Email
def initialize(from, to, subject, body, options={})
@opts = {:attachments => [], :server => 'localhost'}.update(options)
@msg =
@msg.from = from = to
@msg.subject = subject = @opts[:cc] if @opts[:cc]
@msg.bcc = @opts[:bcc] if @opts[:bcc]
if @opts[:attachments].empty?
# just specify the body
@msg.body = body
# attach attachments, including the body
@msg.body = "This is a multi-part message in MIME format.\n"
msg_body =
msg_body.body = body
msg_body.set_content_type("text","plain", {:charset => "ISO-8859-1"}) << msg_body
octet_stream = MIME::Types['application/octet-stream'].first
@opts[:attachments].select {|file| File.readable?(file)}.each do |file|
mime_type = MIME::Types.type_for(file).first || octet_stream << create_attachment(file, mime_type)
attr_reader :msg
def create_attachment(file, mime_type)
attach =
if mime_type.binary?
attach.body = Base64.encode64(
attach.transfer_encoding = 'base64'
attach.body =
attach.set_disposition("attachment", {:filename => file})
attach.set_content_type(mime_type.media_type, mime_type.sub_type, {:name=>file})
# instance method to send an Email object
def send
args = @opts.values_at(:server, :port, :helo, :username, :password, :authtype)
Net::SMTP.start(*args) do |smtp|
smtp.send_message(@msg.to_s, @msg.from[0],
# class method to construct an Email object and send it
def self.send(*args)*args).send
'[email protected]',
%w{ recip1@recipient.invalid },
'the subject',
"the body\nhas lines",
:attachments => %w{ file1 file2 file3 },
:server => '',
:helo => 'sender.invalid',
:username => 'user',
:password => 'secret'

[edit] SAS

filename msg email
to="[email protected]"
cc="[email protected]"
subject="Important message"
data _null_;
file msg;
put "Hello, Connected World!";

[edit] Scala

Library: Scala
import java.util.Properties
import javax.mail.internet.{ InternetAddress, MimeMessage }
import javax.mail.Message.RecipientType
import javax.mail.{ Session, Transport }
/** Mail constructor.
* @constructor Mail
* @param host Host

class Mail(host: String) {
val session = Session.getDefaultInstance(new Properties() { put("", host) })
/** Send email message.
* @param from From
* @param tos Recipients
* @param ccs CC Recipients
* @param subject Subject
* @param text Text
* @throws MessagingException

def send(from: String, tos: List[String], ccs: List[String], subject: String, text: String) {
val message = new MimeMessage(session)
message.setFrom(new InternetAddress(from))
for (to <- tos)
message.addRecipient(RecipientType.TO, new InternetAddress(to))
for (cc <- ccs)
message.addRecipient(RecipientType.TO, new InternetAddress(cc))

[edit] Tcl

Library: Tcllib (Package: mime)
Library: Tcllib (Package: smtp)

Also may use the tls package (needed for sending via gmail).

package require smtp
package require mime
package require tls
set gmailUser *******
set gmailPass hunter2; # Hello,!
proc send_simple_message {recipient subject body} {
global gmailUser gmailPass
# Build the message
set token [mime::initialize -canonical text/plain -string $body]
mime::setheader $token Subject $subject
# Send it!
smtp::sendmessage $token -userame $gamilUser -password $gmailPass \
-recipients $recipient -servers -ports 587
# Clean up
mime::finalize $token
send_simple_message [email protected] "Testing" "This is a test message."


works only with Windows, on Linux OS it is possible to send an email by using the Execute function

system=SYSTEM ()
IF (system=="WIN") THEN
SET to="[email protected]"
SET cc="[email protected]"
DATA how are you?
status = SEND_MAIL (to,cc,subject,text,-)

[edit] TXR

@(next :args)
@ (maybe)
@ (or)
@ (bind CC "")
@ (end)
@ (throw error "must specify at least To and Subject")
@(next "-")
@(output `!mail -s "@SUBJ" -c "@CC" "@TO"`)

Test run:

$ ./sendmail.txr [email protected] "Patch to rewrite scheduler #378"
Here we go
again ...

[edit] VBScript

Function send_mail(from,recipient,cc,subject,message)
With CreateObject("CDO.Message")
.From = from
.To = recipient
.CC = cc
.Subject = subject
.Textbody = message
.Configuration.Fields.Item _
("") = 2
.Configuration.Fields.Item _
("") = _
.Configuration.Fields.Item _
("") = 25
End With
End Function
Call send_mail("[email protected]","[email protected]","","Test Email","this is a test message")
Personal tools