Send email: Difference between revisions

40,998 bytes added ,  1 month ago
Added FreeBASIC
No edit summary
(Added FreeBASIC)
 
(46 intermediate revisions by 18 users not shown)
Line 1:
{{task|Networking and Web Interaction}}
{{task|Networking and Web Interaction}}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.
 
;Task:
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.
Line 10 ⟶ 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 37 ⟶ 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 78 ⟶ 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 166 ⟶ 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">
 
#include <curl/curl.h>
#include <string.h>
#include <stdio.h>
 
#define from "<sender@duniya.com>"
#define to "<addressee@gmail.com>"
#define cc "<info@example.org>"
static const char *payload_text[] = {
"Date: Mon, 13 Jun 2018 11:30:00 +0100\r\n",
"To: " to "\r\n",
"From: " from " (Example User)\r\n",
"Cc: " cc " (Another example User)\r\n",
"Message-ID: <ecd7db36-10ab-437a-9g3a-e652b9458efd@"
"rfcpedant.example.org>\r\n",
"Subject: Sanding mail via C\r\n",
"\r\n",
"This mail is being sent by a C program.\r\n",
"\r\n",
"It connects to the GMail SMTP server, by far, the most popular mail program of all.\r\n",
"Which is also probably written in C.\r\n",
"To C or not to C..............\r\n",
"That is the question.\r\n",
NULL
};
struct upload_status {
int lines_read;
};
static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)
{
struct upload_status *upload_ctx = (struct upload_status *)userp;
const char *data;
if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) {
return 0;
}
data = payload_text[upload_ctx->lines_read];
if(data) {
size_t len = strlen(data);
memcpy(ptr, data, len);
upload_ctx->lines_read++;
return len;
}
return 0;
}
int main(void)
{
CURL *curl;
CURLcode res = CURLE_OK;
struct curl_slist *recipients = NULL;
struct upload_status upload_ctx;
upload_ctx.lines_read = 0;
curl = curl_easy_init();
if(curl) {
 
curl_easy_setopt(curl, CURLOPT_USERNAME, "user");
curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret");
 
curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:465");
 
curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem");
 
curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from);
 
recipients = curl_slist_append(recipients, to);
recipients = curl_slist_append(recipients, cc);
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
 
curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
 
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
 
res = curl_easy_perform(curl);
 
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
 
curl_slist_free_all(recipients);
 
curl_easy_cleanup(curl);
}
return (int)res;
}
</syntaxhighlight>
 
=={{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 173 ⟶ 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 218 ⟶ 356:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
When run literally as above, should print:
Line 227 ⟶ 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 261 ⟶ 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 271 ⟶ 380:
:cc ["bob@builder.com" "dora@explorer.com"]
:subject "Yo"
:body "Testing."})</langsyntaxhighlight>
 
{{out}}
Line 278 ⟶ 387:
=={{header|D}}==
Requires the libcurl library to be installed on the system.
<langsyntaxhighlight lang="d">void main() {
import std.net.curl;
 
Line 287 ⟶ 396:
s.message = "Subject:test\n\nExample Message";
s.perform;
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
procedure SendEmail;
var
Line 324 ⟶ 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 330 ⟶ 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 342 ⟶ 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 351 ⟶ 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 359 ⟶ 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 398 ⟶ 541:
}
}
</syntaxhighlight>
</lang>
 
=={{header|GoFortran}}==
===Intel Fortran on Windows===
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).
 
<syntaxhighlight lang="fortran">program sendmail
use ifcom
use msoutl
implicit none
integer(4) :: app, status, msg
call cominitialize(status)
call comcreateobject("Outlook.Application", app, status)
msg = $Application_CreateItem(app, olMailItem, status)
call $MailItem_SetTo(msg, "somebody@somewhere", status)
call $MailItem_SetSubject(msg, "Title", status)
call $MailItem_SetBody(msg, "Hello", status)
call $MailItem_Send(msg, status)
call $Application_Quit(app, status)
call comuninitialize()
end program</syntaxhighlight>
 
=={{header|FreeBASIC}}==
===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 565 ⟶ 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 617 ⟶ 857:
/*Call function */
simpleMail(s1, s2 , s3, "TITLE", "TEXT");
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
 
Example using [https://hackage.haskell.org/package/smtp-mail <tt>smtp-mail</tt>] package:
 
<syntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
 
module Main (main) where
 
import Network.Mail.SMTP
( Address(..)
, htmlPart
, plainTextPart
, sendMailWithLogin'
, simpleMail
)
 
main :: IO ()
main =
sendMailWithLogin' "smtp.example.com" 25 "user" "password" $
simpleMail
(Address (Just "From Example") "from@example.com")
[Address (Just "To Example") "to@example.com"]
[] -- CC
[] -- BCC
"Subject"
[ plainTextPart "This is plain text."
, htmlPart "<h1>Title</h1><p>This is HTML.</p>"
]</syntaxhighlight>
 
==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 628 ⟶ 897:
every write(mail , !&input)
close (mail)
end</langsyntaxhighlight>
 
=={{header|Java}}==
 
<langsyntaxhighlight lang="java5">import java.util.Properties;
 
import javax.mail.MessagingException;
Line 687 ⟶ 956:
Transport.send(message);
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
using SMTPClient
 
addbrackets(s) = replace(s, r"^\s*([^\<\>]+)\s*$", s"<\1>")
 
function wrapRFC5322(from, to, subject, msg)
timestr = Libc.strftime("%a, %d %b %Y %H:%M:%S %z", time())
IOBuffer("Date: $timestr\nTo: $to\nFrom: $from\nSubject: $subject\n\n$msg")
end
 
function sendemail(from, to, subject, messagebody, serverandport;
cc=[], user="", password="", isSSL=true, blocking=true)
opt = SendOptions(blocking=blocking, isSSL=isSSL, username=user, passwd=password)
send(serverandport, map(s -> addbrackets(s), vcat(to, cc)), addbrackets(from),
wrapRFC5322(addbrackets(from), addbrackets(to), subject, messagebody), opt)
end
 
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>
 
=={{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.
<syntaxhighlight lang="scala">// version 1.1.4-3
 
import java.util.Properties
import javax.mail.Authenticator
import javax.mail.PasswordAuthentication
import javax.mail.Session
import javax.mail.internet.MimeMessage
import javax.mail.internet.InternetAddress
import javax.mail.Message.RecipientType
import javax.mail.Transport
 
fun sendEmail(user: String, tos: Array<String>, ccs: Array<String>, title: String,
body: String, password: String) {
val props = Properties()
val host = "smtp.gmail.com"
with (props) {
put("mail.smtp.host", host)
put("mail.smtp.port", "587") // for TLS
put("mail.smtp.auth", "true")
put("mail.smtp.starttls.enable", "true")
}
val auth = object: Authenticator() {
protected override fun getPasswordAuthentication() =
PasswordAuthentication(user, password)
}
val session = Session.getInstance(props, auth)
val message = MimeMessage(session)
with (message) {
setFrom(InternetAddress(user))
for (to in tos) addRecipient(RecipientType.TO, InternetAddress(to))
for (cc in ccs) addRecipient(RecipientType.TO, InternetAddress(cc))
setSubject(title)
setText(body)
}
val transport = session.getTransport("smtp")
with (transport) {
connect(host, user, password)
sendMessage(message, message.allRecipients)
close()
}
}
 
fun main(args: Array<String>) {
val user = "some.user@gmail.com"
val tos = arrayOf("other.user@otherserver.com")
val ccs = arrayOf<String>()
val title = "Rosetta Code Example"
val body = "This is just a test email"
val password = "secret"
sendEmail(user, tos, ccs, title, body, password)
}</syntaxhighlight>
 
=={{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 727 ⟶ 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 757 ⟶ 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}}
<syntaxhighlight lang="lingo">----------------------------------------
-- Sends email via SMTP using senditquiet.exe (15 KB)
-- @param {string} fromAddr
-- @param {string} toAddr - multiple addresses separated with ;
-- @param {string} subject
-- @param {string} message - use "\n" for line breaks
-- @param {string} [cc=VOID] - optional; multiple addresses separated with ;
-- @param {string} [bcc=VOID] - optional; multiple addresses separated with ;
-- @param {propList} [serverProps=VOID] - optional; allows to overwrite default settings
-- @return {bool} success
----------------------------------------
on sendEmail (fromAddr, toAddr, subject, message, cc, bcc, serverProps)
sx = xtra("Shell").new()
-- senditquiet.exe in folder "bin" relative to current movie
sx.shell_setcurrentdir(_movie.path&"bin")
-- defaults
host = "smtp.gmail.com"
protocol = "ssl"
port = 587
user = "johndoe"
pass = "foobar"
-- if propList 'serverProps' was passed, overwrite defaults
if ilk(serverProps)=#propList then
repeat with i = 1 to serverProps.count
do(serverProps.getPropAt(i)&"="&QUOTE&serverProps[i]&QUOTE)
end repeat
end if
 
cmd = "senditquiet"
put " -s "&host after cmd
put " -protocol "&protocol after cmd
put " -port "&port after cmd
put " -u "&user after cmd
put " -p "&pass after cmd
put " -f "&QUOTE&fromAddr&QUOTE after cmd
put " -t "&QUOTE&toAddr&QUOTE after cmd
put " -subject "&QUOTE&subject&QUOTE after cmd
put " -body "&QUOTE&message&QUOTE after cmd
-- optional args
if not voidP(cc) then put " -cc "&QUOTE&cc&QUOTE after cmd
if not voidP(bcc) then put " -bcc "&QUOTE&bcc&QUOTE after cmd
 
put " 1>nul 2>nul & if errorlevel 1 echo ERROR" after cmd
res = sx.shell_cmd(cmd)
return not(res contains "ERROR")
end</syntaxhighlight>
 
=={{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 775 ⟶ 1,174:
doc.SendTo = "John Doe"
doc.Subject = "Subject of this mail"
Call doc.Send( False )</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 781 ⟶ 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 812 ⟶ 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 834 ⟶ 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 861 ⟶ 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 875 ⟶ 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 887 ⟶ 1,287:
# Authen::SASL here.
 
sub send_email {
{ my %o =
(from => '', to => [], cc => [],
subject => '', body => '',
Line 895 ⟶ 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 912 ⟶ 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 924 ⟶ 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 957 ⟶ 1,357:
send_email('from-me@example.com', 'to-foo@example.com', '',
"very important subject",
"Body text\n");</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/libcurl}}
{{trans|C}}
Obviously, USER/PWD/URL/etc. would all need altering for your details.
For gmail, make sure you enable https://myaccount.google.com/lesssecureapps
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (libcurl)</span>
<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>
<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>
<span style="color: #000000;">PWD</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"secret"</span><span style="color: #0000FF;">,</span>
<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>
<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>
<span style="color: #008000;">"To: %s\r\n"</span><span style="color: #0000FF;">&</span>
<span style="color: #008000;">"From: %s (Example User)\r\n"</span><span style="color: #0000FF;">&</span>
<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>
<span style="color: #008000;">"\r\n"</span><span style="color: #0000FF;">&</span>
<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>
<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>
<span style="color: #008000;">"Which is, however, probably not written in Phix.\r\n"</span>
<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>
<span style="color: #000080;font-style:italic;">-- copy a maximum of size*nmemb bytes into pbuffer</span>
<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>
<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>
<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>
<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>
<span style="color: #000000;">sent</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">bytes_written</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;">sent</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">machine_word</span><span style="color: #0000FF;">())</span>
<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>
<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>
<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>
<span style="color: #004080;">atom</span> <span style="color: #000000;">slist_recipients</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">NULL</span>
<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>
<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>
<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>
<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 974 ⟶ 1,444:
Untested:
 
<langsyntaxhighlight lang="pike">int main(){
string to = "some@email.add";
string subject = "Hello There.";
Line 981 ⟶ 1,451:
Protocols.SMTP.Client()->simple_mail(to,subject,from,msg);
}</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Line 987 ⟶ 1,457:
 
The parameters are splatted with a hashtable:
<syntaxhighlight lang="powershell">
<lang PowerShell>
[hashtable]$mailMessage = @{
From = "weirdBoy@gmail.com"
Line 1,002 ⟶ 1,472:
 
Send-MailMessage @mailMessage
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight Purebasiclang="purebasic">InitNetwork()
 
CreateMail(0, "from@mydomain.com", "This is the Subject")
Line 1,019 ⟶ 1,489:
Else
MessageRequester("Error", "Can't sent the mail !")
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
===Python: POSIX===
 
The function returns a dict of any addresses it could not forward to;
other connection problems raise [http://docs.python.org/library/smtplib.html?highlight=smtplib#smtplib.SMTP.sendmail errors].<br>
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,044 ⟶ 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,053 ⟶ 1,523:
message = 'Howdy from a python function',
login = 'pythonuser',
password = 'XXXXX')</langsyntaxhighlight>
 
{{out|Sample Email received}}
Line 1,065 ⟶ 1,535:
Howdy from a python function
</pre>
 
===Python: Windows===
Using Outlook COM server with the Pywin32 library.
 
<syntaxhighlight lang="python">import win32com.client
 
def sendmail(to, title, body):
olMailItem = 0
ol = win32com.client.Dispatch("Outlook.Application")
msg = ol.CreateItem(olMailItem)
msg.To = to
msg.Subject = title
msg.Body = body
msg.Send()
ol.Quit()
 
sendmail("somebody@somewhere", "Title", "Hello")</syntaxhighlight>
 
=={{header|R}}==
R does not have a built-in facility for sending emails though there is a package for this on CRAN: '''[https://cran.r-project.org/web/packages/mail/ mail]'''.
{{libheader|tcltk}}
 
===Windows===
{{libheader|gdata}}
Using Outlook COM server with the '''[http://www.omegahat.net/RDCOMClient/ RDCOMClient]''' package.
 
<syntaxhighlight lang="r">library(RDCOMClient)
{{libheader|caTools}}
 
send.mail <- function(to, title, body) {
olMailItem <- 0
ol <- COMCreate("Outlook.Application")
msg <- ol$CreateItem(olMailItem)
msg[["To"]] <- to
msg[["Subject"]] <- title
msg[["Body"]] <- body
msg$Send()
ol$Quit()
}
 
send.mail("somebody@somewhere", "Title", "Hello")</syntaxhighlight>
R does not have a built-in facility for sending emails though some code for this, written by Ben Bolker, is available [http://people.biology.ufl.edu/bolker/Rmail.r here].
 
=={{header|Racket}}==
 
Racket has a built-in library for sending e-mails:
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,103 ⟶ 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}}==
There is a REXX program to send email via REXX, &nbsp; I'm trying to locate the author to get permission to include it here on Rosetta Code. <br><br>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
load "stdlib.ring"
See "Send email..." + nl
sendemail("smtp://smtp.gmail.com",
"calmosoft@gmail.com",
"password",
"calmosoft@gmail.com",
"calmosoft@gmail.com",
"calmosoft@gmail.com",
"Sending email from Ring",
"Hello
How are you?
Are you fine?
Thank you!
Greetings,
CalmoSoft")
see "Done.." + nl
</syntaxhighlight>
Output:
<pre>
Hello
How are you?
Are you fine?
Thank you!
Greetings,
CalmoSoft
</pre>
 
=={{header|Ruby}}==
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,190 ⟶ 1,772:
:password => 'secret'
}
)</langsyntaxhighlight>
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">filename msg email
to="afriend@someserver.com"
cc="anotherfriend@somecompany.com"
Line 1,202 ⟶ 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,239 ⟶ 1,821:
Transport.send(message)
}
}</langsyntaxhighlight>
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
You must first set the SMTP server in the database from which you want to send the message.
<syntaxhighlight 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>
Output:
<pre>
db2 => UPDATE DB CFG FOR myDb USING SMTP_SERVER 'smtp.ibm.com';
DB20000I The UPDATE DATABASE CONFIGURATION command completed successfully.
db2 => CALL UTL_MAIL.SEND ('senderAccount@myDomain.com','recipientAccount@yourDomain.com', NULL, NULL, 'The subject of the message', 'The content of the message');
 
Return Status = 0
</pre>
If you receive a "SQL1336N The remote host "smtp.ibm.com" was not found. SQLSTATE=08001" message, it is because the SMTP_SERVER is not valid.
More information in the [https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.apdv.sqlpl.doc/doc/r0055177.html IBM Knowledge center]
 
=={{header|Tcl}}==
{{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,266 ⟶ 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,285 ⟶ 1,887:
 
ENDIF
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
<langsyntaxhighlight lang="txr">#!/usr/bin/txr
#!/usr/bin/txr
@(next :args)
@(cases)
Line 1,311 ⟶ 1,912:
@(end)
.
@(end)</langsyntaxhighlight>
 
{{out}}
Line 1,330 ⟶ 1,931:
{{omit from|zkl}}
{{omit from|ZX Spectrum Basic|Does not have network access.}}
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Option Explicit
Const olMailItem = 0
 
Sub SendMail(MsgTo As String, MsgTitle As String, MsgBody As String)
Dim OutlookApp As Object, Msg As Object
Set OutlookApp = CreateObject("Outlook.Application")
Set Msg = OutlookApp.CreateItem(olMailItem)
With Msg
.To = MsgTo
.Subject = MsgTitle
.Body = MsgBody
.Send
End With
Set OutlookApp = Nothing
End Sub
 
Sub Test()
SendMail "somebody@somewhere", "Title", "Hello"
End Sub</syntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function send_mail(from,recipient,cc,subject,message)
With CreateObject("CDO.Message")
Line 1,353 ⟶ 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