Skip to content

Instantly share code, notes, and snippets.

@WhoAteDaCake
Last active October 13, 2018 09:40
Show Gist options
  • Save WhoAteDaCake/8f4df57291d0f98a26f7e33c0c45dc6e to your computer and use it in GitHub Desktop.
Save WhoAteDaCake/8f4df57291d0f98a26f7e33c0c45dc6e to your computer and use it in GitHub Desktop.
Sending mail using reasonml and ocamlnet
/* Has side-effects */
module Option = Core.Option;
let enable_debug_sf = () => Netsmtp.Debug.enable := true;
type mail_client = {
domain: string,
client: Netsmtp.client,
tls: (module Netsys_crypto_types.TLS_CONFIG),
};
let default_timeout = 60.0;
let create = (~timeout=?, domain, port) => {
let timeout = Option.value(timeout, ~default=default_timeout);
let provider = Netsys_crypto.current_tls();
let address =
`Socket((
`Sock_inet_byname((Unix.SOCK_STREAM, domain, port)),
Uq_client.default_connect_options,
));
let tls =
Netsys_tls.create_x509_config(
~peer_auth=`None,
~system_trust=true,
provider,
);
let client = (new Netsmtp.connect)(address, timeout);
{domain, client, tls};
};
let authenticate = (user, password, mail_client) => {
mail_client.client#helo() |> ignore;
mail_client.client#starttls(
mail_client.tls,
~peer_name=Some(mail_client.domain),
);
mail_client.client#auth(
(module Netmech_plain_sasl.PLAIN),
user,
"",
[("password", password, [])],
[],
);
mail_client;
};
let send_mail_sf = (mail, mail_client) => {
Netsmtp.sendmail(mail_client.client, mail);
mail_client;
};
Nettls_gnutls.init() |> ignore;
let mail =
Netsendmail.compose(
~from_addr=("Test user", Config.emailUser),
~to_addrs=[("Recipient", Config.emailRecipient)],
~subject="Test subject2",
"Hello, this is a test email 2",
);
let _ =
Mail_client.create("smtp.gmail.com", 587)
|> Mail_client.authenticate(Config.emailUser, Config.emailPass)
|> Mail_client.send_mail_sf(mail);
@WhoAteDaCake
Copy link
Author

Requires:

opam install conf-gnutls # Will require gnutls in the system
opam install ocamlnet
opam install core # Optional

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment