Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs

Page created by Shane Soto
 
CONTINUE READING
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
mailsac-examples Documentation

                Forking Software LLC

                           Sep 13, 2020
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
General

1   Table of Contents         3

                              i
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
ii
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
mailsac-examples Documentation

Welcome to the official documentation for Mailsac, the disposable email service built for developers.
Mailsac accepts nearly all email, like a fake SMTP server. You can fetch and manage email using simple REST APIs,
WebSockets, and Webhooks; route mail to Slack, or check it with POP3.
Newcomers may want to look at the introduction page to get an overview of what Mailsac has to offer.

General                                                                                                        1
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
mailsac-examples Documentation

2                                General
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
CHAPTER              1

                                                                                         Table of Contents

1.1 Introduction

With Mailsac, it is easy to interact with email via REST API, Webhooks and WebSockets. You can reserve and release
email addresses, check messages, download attachments, and route mail.

Tip: All REST API endpoints can be found in the API Specification

1.1.1 cURL REST API Example

In this example, we are fetching messages sent to the email address user1@mailsac.com.

curl -H 'Mailsac-Key: YOUR_API_KEY_HERE' https://mailsac.com/api/addresses/
 ˓→user1@mailsac.com/messages

Information about the most recent email is returned as JSON

[{
     "_id": "BotvTxaona7gLID1Adtpfj8Fnfi7HSSv-0",
     "from": [
       {
         "address": "microsoftstore@e.microsoft.com",
         "name": "Microsoft Store"
       }
     ],
     "to": [
       {
         "address": "user1@mailsac.com",
         "name": ""
                                                                                              (continues on next page)

                                                                                                                    3
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
mailsac-examples Documentation

                                                                                            (continued from previous page)
     }
   ],
   "cc": null,
   "bcc": null,
   "subject": "Ahoy, Sea of Thieves for PC is here",
   "savedBy": null,
   "originalInbox": "inbox-c942bfeeafb96c0e5ce8b4e5c0d747c608@mailsac.com",
   "inbox": "user1@mailsac.com",
   "domain": "mailsac.com",
   "received": "2018-03-29T18:28:07.732Z",
   "size": 23420,
   "attachments": ["c830ee26e0a326e0a30c585494793479"],
   "ip": "65.55.234.211",
   "via": "144.202.71.79",
   "folder": "inbox",
   "labels": [],
   "read": null,
   "rtls": true,
   "links": [
     "https://support.xbox.com/games/game-titles/xbox-play-anywhere-help",
     "https://e.microsoft.com/Key-3567701.C.CQZpy.J.K0.-.CpMBp0",
     "https://account.microsoft.com/profile/unsubscribe?CTID=0&
 ˓→ECID=jIce0uXtDC5qRlyCYqZsz5yCL"

   ],
   "spam": 0.331
}]

Tip: This may look for more information than you need. But it provides a great example of all the hard work Mailsac
has done to make parsing of email easier.

1.2 Frequently Asked Questions

1.2.1 Where are my email attachments?

Email attachments are not viewable for public addresses from the Website. Attachments must be downloaded using
REST API.
Attachments on emails sent to Private Addresses can be viewed in the Unified Inbox or in an email client using POP3.
Read more about email attachments at Mailsac.

1.2.2 Why would I use Mailsac?

Any time you need a temporary email address, just make one up@mailsac.com.
If you need to test your email system, send it to mailsac.com - even for a custom domain.
Other uses:
    • avoid spam by keeping your real email address private
    • create an account on a website without disclosing your real email address
    • give it out to strangers

4                                                                                 Chapter 1. Table of Contents
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
mailsac-examples Documentation

    • use it as a shared email address
    • send mail to Mailsac for QA testing purposes
    • use it when you (legally) want to receive email without disclosing your identity
    • send to an email address or multiple email addresses without needing to create them
    • as a developer, to test that your application is sending email

1.2.3 Why weren’t my messages received?

There are many reasons messages may not be received or displayed by Mailsac.
The Missing Email page provides detailed explanations about why messages are not received.
Most often, the following happens:
   1. The sender blocks traffic to disposable email providers like Mailsac. This is common with email signups or
      email verifications. People running websites do not want a bunch of spam accounts.
   2. Large message size. Mailsac only supports messages up to about 2 MB.
   3. Fast recycling. Without enough message storage, your inbound emails may be deleted quickly.
   4. Throttling. Non-paying customers can be throttled for sending too much. We are happy to lift this for paying
      customers. Custom Domain are not throttled.
The Mailsac Team is highly responsive to forum and support emails. Contact us and we will resolve your issue.

Tip: https://forum.mailsac.com
support@team.mailsac.com

1.2.4 Can I use Mailsac for testing purposes?

Absolutely!
We love to hear from developers that use Mailsac - contact us anytime.
Throttling may occur when sending. Avoid throttling by using a Custom Domain

1.2.5 How long is email saved?

Email messages that are sent to public domains ( ie mailsac.com) are retained for 4 days and have a max number of 6
messages per inbox.
Message storage prevents emails from being recycled.
   1. If you star a message, it will not be recycled until you unstar it.
   2. Private addresses will not be recycled, up to your storage limit.
   3. Messages on custom domains will not be recycled, up to your storage limit.

1.2.6 Can other people see messages that I starred?

Nope. Only you can see them when you are logged in.

1.2. Frequently Asked Questions                                                                                  5
Mailsac-examples Documentation - Forking Software LLC - Sep 13, 2020 - Docs
mailsac-examples Documentation

1.2.7 How do I reply to my Mailsac emails?

You must create an account to reply to emails. New accounts have 5 sending credits. Additional credits can be
purchased _.
You can use POP3 to download messages on a private address or custom domain. Responses can be sent from non-
mailsac accounts you have configured your email client to use.

1.3 REST API - Getting Started

This example will show how to do the following using the REST API.
    • list emails sent to user1@mailsac.com
    • read an email sent to user1@mailsac.com
    • send an email from user1@mailsac.com
user1@mailsac.com can be replaced with any email address hosted by Mailsac. If you are familiar with REST APIs
the REST API Specification can be referenced during this example.

1.3.1 REST API Overview

REST API interaction is at the core of Mailsac. The examples in this section will provide you with easy to understand
curl examples. For additional code examples (Nodejs and Python) see: Reading Email and Sending Mail.

1.3.2 Prerequisites

API access is included with all Mailsac accounts. Create or view your API key. Your API key will be used as the value
for the Mailsac-Key Authentication Header.
curl is the only program used in this example. If you are using Linux or OS X curl is likely already installed. The
following commands can be used to install curl.

                                    Listing 1: For operating systems using yum
sudo yum install curl -y

                                     Listing 2: For operating system using apt
sudo apt-get install curl -y

                                                Listing 3: For OS X
brew install curl

                       Listing 4: For Windows’s Operating System using Chocolately Nuget.
chocolately install curl

Tip: jq can be used to parse JSON, making the output from curl pretty.

6                                                                                 Chapter 1. Table of Contents
mailsac-examples Documentation

1.3.3 Get Mail

To list the available messages for user1@mailsac.com we will use the /api/addresses/:email/messages
endpoint. This endpoint accepts one parameter :email. After substituting the :email parameter and providing the
required Authentication Header, the following curl command will return JSON.

                                 Listing 5: Retrieve list of messages in an inbox.
curl -H 'Mailsac-Key: YOUR_API_KEY_HERE' https://mailsac.com/api/addresses/
 ˓→user1@mailsac.com/messages

                                            Listing 6: Inbox messages
[{
   "_id": "BotvTxaona7gLID1Adtpfj8Fnfi7HSSv-0",
   "from": [
     {
       "address": "microsoftstore@e.microsoft.com",
       "name": "Microsoft Store"
     }
   ],
   "to": [
     {
       "address": "user1@mailsac.com",
       "name": ""
     }
   ],
   "cc": null,
   "bcc": null,
   "subject": "Ahoy, Sea of Thieves for PC is here",
   "savedBy": null,
   "originalInbox": "inbox-c942bfeeafb96c0e5ce8b4e5c0d747c608@mailsac.com",
   "inbox": "user1@mailsac.com",
   "domain": "mailsac.com",
   "received": "2018-03-29T18:28:07.732Z",
   "size": 23420,
   "attachments": ["c830ee26e0a326e0a30c585494793479"],
   "ip": "65.55.234.211",
   "via": "144.202.71.79",
   "folder": "inbox",
   "labels": [],
   "read": null,
   "rtls": true,
   "links": [
     "https://support.xbox.com/games/game-titles/xbox-play-anywhere-help",
     "https://e.microsoft.com/Key-3567701.C.CQZpy.J.K0.-.CpMBp0",
     "https://account.microsoft.com/profile/unsubscribe?CTID=0&
 ˓→ECID=jIce0uXtDC5qRlyCYqZsz5yCL"

   ],
   "spam": 0.331
}]

The returned JSON contains metadata about the email message including to address, from address, subject, time stamp,
attachments and much more. Make note of the _id field, it will be used it to view the contents of the email.

Tip: API documentation is generalized. Modifications are needed to translate an API endpoint into a usable URL.

1.3. REST API - Getting Started                                                                                   7
mailsac-examples Documentation

The base URI of all Mailsac API requests will be https://mailsac.com.

1.3.4 Read Mail

To read an email message we will use the /api/text/:email/:messageId endpoint. This endpoint requires
two parameters, :email and :messageId. After substituting the :email and :messageId parameters and
providing the required Authentication Header, the following curl command will return a plain-text version of the
message.

                                        Listing 7: Retrieve text of message
curl -H "Mailsac-Key: YOUR_API_KEY_HERE" https://mailsac.com/api/text/user1@mailsac.
 ˓→com/Jn1wa9AwLigQwIbwUGyMMollJkeWSeUd-0

                                       Listing 8: Plain text email message
Enjoy odoo partnership program and success pack sales combo! *
Summer is around the corner! Odoo wishes to save your time and effort from
 ˓→complicated paperwork for more outdoor activities!   Therefore, we are offering an
 ˓→exclusive discount for Partnership in MAY.

Partnership program pricing at USD 2950
* and save USD 1000* on your joining!
* *The discount offer is only applicable for the purchase with a success pack.

Schedule a demo with
Odoo Partnership Expert* BOOK NOW [2]
Our Partnership
Program* READ MORE [3]
* Our Worldwide Partners* READ MORE [4]
* Our Customers success story* READ MORE [5]
None [6] None [7] None [8] None [9]
Unsubscribe [10] | Contact [11]
2018 All Rights Reserved

[1] https://www.odoo.com/r/erT/m/12928017
[2] https://www.odoo.com/r/X6Q/m/12928017
[3] https://www.odoo.com/r/so8/m/12928017
[4] https://www.odoo.com/r/fya/m/12928017
[5] https://www.odoo.com/r/jlI/m/12928017
[6] https://www.odoo.com/r/dlt/m/12928017
[7] https://www.odoo.com/r/25S/m/12928017
[8] https://www.odoo.com/r/Vcu/m/12928017
[9] https://www.odoo.com/r/nKf/m/12928017
[10] https://www.odoo.com/unsubscribe_from_list
[11] https://www.odoo.com/r/rox/m/12928017

The /text/ portion of the URL can be replaced with other values, to retrieve different parsed representations of the
SMTP body.
    • /text/ plaintext email body, or HTML parsed to plaintext
    • /raw/ entire received SMTP message including headers, body, and attachments
    • /body/ HTML body, with images, links and scripts scrubbed

8                                                                                Chapter 1. Table of Contents
mailsac-examples Documentation

    • /dirty/ HTML body, with nothing scrubbed and images inlined
    • /headers/ JSON object representation of SMTP headers. The key will be the header key, lowercased. When
      there are multiple headers with the same name , such as Received header, the value of the header will be an
      array of strings. Otherwise the value will be a string.

1.3.5 Sending Mail

Important: Sending messages requires the purchase of outgoing message credits, unless you are sending interally,
within a custom domain hosted by Mailsac.

To send an email from user1@mailsac.com we will use the /api/outgoing-messages endpoint. This API
endpoint uses a POST method, unlike our previous two examples, and accepts the following parameters in a JSON
body.
    • Mailsac-Key header with your API key
    • to address
    • from address
    • subject subject
    • text message text body
The /api/outgoing-messages endpoint expects a JSON encoded body,                             a Content-Type:
application/json header, and a Authentication Header.

                                             Listing 9: Send an email
curl -H "Content-Type: application/json" \
     -H "Mailsac-Key: YOUR_API_KEY_HERE" \
     -X POST \
     --data '{"to": "recipient@mailsac.com.com", "subject": "This is a test", "from":
 ˓→"my_sender@mailsac.com", "text": "This is a test"}' \

     https://mailsac.com/api/outgoing-messages

1.4 Delivery Confirmation Example

Consider a scenario, where you have an automated process that sends emails. You may wish to test that this automated
process is sending emails and they are being received. Mailsac provides an API so you can check that these emails are
being received.

1.4.1 Prerequisites

    • Python3
    • Mailsac API Key
This python example sends emails to user1@mailsac.com through user10@mailsac.com using an SMTP server. Your
mail server may or may not use authentication, in this example we are using authentication with TLS.

1.4. Delivery Confirmation Example                                                                                 9
mailsac-examples Documentation

""" This script is an example of sending an email via smtp
and confirming its receipt using the mailsac api"""

import time
import sys
import smtplib
import email.utils
import requests
from email.mime.text import MIMEText

"""
Checks if a message from a given address in the a specific mailsac
inbox. If it is it returns when the message was recived, if not it returns
a message stating the message was not received"""
def check_received(receive_address, send_address, base_url, headers):
     api_url = '{0}/addresses/{1}/messages'.format(base_url, receive_address)
     response = requests.get(api_url, headers=headers)
     for message in response.json():
         if message['from'][0]['address'] == send_address:
             return message['received']
         return '{0} has not received an email from {1}'.format(receive_address, send_
 ˓→address)

SMTP_USERNAME = 'mysmtp_user'
SMTP_PASSWORD = 'mysmtp_password'
SMTP_SERVER = 'mysmtp_server.company.com'
SMTP_PORT = 587
FROM_ADDRESS = 'myuser@company.com'
FROM_NAME = 'MyTest User'
SUBJECT = "Testing email to mailsac"

API_TOKEN = 'MY_API_TOKEN_FROM_MAILSAC'
BASE_URL = 'https://mailsac.com/api/'

BODY_TEXT = ("Mailsac SMTP Validate Emila Send\r\n"
              "This email was sent using the SMTP to test receipt of an email."
            )

for x in range(1, 10):
    try:
         to_address = 'user{}@mailsac.com'.format(x)
         msg = MIMEText(BODY_TEXT)
         msg['Subject'] = SUBJECT
         msg['From'] = email.utils.formataddr((FROM_NAME, FROM_ADDRESS))
         msg['To'] = to_address

        conn = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        conn.set_debuglevel(True)
        conn.ehlo()
        conn.starttls()
        conn.ehlo()
        conn.login(SMTP_USERNAME, SMTP_PASSWORD)
        try:
             conn.sendmail(FROM_ADDRESS, to_address, msg.as_string())
             conn.close()
        except Exception as e:
                                                                           (continues on next page)

10                                                            Chapter 1. Table of Contents
mailsac-examples Documentation

                                                                                            (continued from previous page)
             print("Error: ", e)
         else:
             print("Email Sent!")
     except Exception as ex:
         print(ex)

time.sleep(30)

for x in range(1, 10):
    print(check_received('user{}@mailsac.com'.format(x), send_address=FROM_ADDRESS,
                       base_url=BASE_URL, headers={'Mailsac-Key': API_TOKEN}))

1.5 Download All Inbox Attachments

This is a step by step coding guide for downloading all of the attachments in a Mailsac email inbox.

1.5.1 Prerequisites

    • Node.js
    • Mailsac API Key

1.5.2 Setup

Choose a folder to work in, and navigate to the folder in your terminal.
Configure the npm package.json:

npm init -y
npm install --save request request-promise-native

Create a file:

touch download-inbox-attachments.js

Now open the .js file and put the following code in. Change the string value of MAILSAC_API_KEY from ‘YOUR
API KEY GOES HERE’ to your actual API key.

const fs = require('fs')
const request = require('request');
const requestp = require('request-promise-native')

const MAILSAC_API_KEY = 'YOUR API KEY GOES HERE';
const address = process.argv[2];

requestp(`https://mailsac.com/api/addresses/${address}/messages`, {
        json: true,
        headers: {
            'Mailsac-Key': MAILSAC_API_KEY
        },
    })
    .then((messages) => {
                                                                                                  (continues on next page)

1.5. Download All Inbox Attachments                                                                                   11
mailsac-examples Documentation

                                                                                               (continued from previous page)
            console.log(`fetched ${messages.length} messages for ${address}`);

        messages.forEach((message) => {
            if (!message.attachments) {
                console.log(`${message.subject.substring(0, 10)}... ${message._id} -
˓→has no attachments`);

                return
            }
            if (message.attachments) {
                console.log(`${message.subject.substring(0, 10)}... ${message._id} -
˓→has ${message.attachments.length} attachments`);

                message.attachments.forEach((checksum) => {
                    const file = fs.createWriteStream(`${checksum}.eml`);
                    request(`https://mailsac.com/api/addresses/${address}/messages/$
˓→{message._id}/attachments/${checksum}`)

                        .pipe(file);
                });
            }
        });
    })
    .catch((err) => {
        console.error('Something broke!', err.message, err.stack);
    });

The script can be run in the terminal like this:

node download-inbox-attachments.js address@mailsac.com

This Node script does a few things:
     1. Takes takes the email address ‘address@mailsac.com’ as an input argument. You can change this to any email
        address.
     2. It fetches the metadata for all messages in the inbox address@mailsac.com.
     3. It loops through the list of messages and prints part of the subject, the unique message identifier, and how many
        attachments it has.
     4. When messages have attachments, the attachment is downloaded into the current folder, using it’s MD5 check-
        sum as an identifier.
That’s it! Read more about message attachment APIs in the docs.

1.6 Verifying Email Addresses

Mailsac has two API endpoints for confirming the validity of email addresses. A single address or bulk addresses
can be checked. This allows verification of an address or group of addresses without sending a mail. It helps avoid
bounces.
Email validation is a useful tool for keeping invalid signups from invading your mailing list. If you run software-as-a-
service, it can be used to keep users from signing up with anonymous or disposable email addresses.
Unlike our competitors, Mailsac has few limitations or costs for verifying email. You can verify single email addresses,
or up to 50 at a time (more coming soon - contact support). We don’t charge extra for these types of API requests.

12                                                                                   Chapter 1. Table of Contents
mailsac-examples Documentation

1.6.1 Prerequisites

    • Node.js
    • Mailsac API Key

1.6.2 Setup

Choose a folder to work in, and navigate to the folder in your terminal.
Configure the npm package.json:

npm init -y
npm install --save request request-promise-native

1.6.3 Single Address Validation

Here is an example for validating a single email address using Node.js:

const requestp = require('request-promise-native')

const MAILSAC_API_KEY = 'YOUR API KEY GOES HERE';
const address = process.argv[2];

requestp(`https://mailsac.com/api/validations/addresses/${address}`, {
        json: true,
        headers: {
            'Mailsac-Key': MAILSAC_API_KEY
        },
    })
    .then((results) => {
        console.log(results[0]);
    })
    .catch((err) => {
        console.error('Something broke!', err.message, err.stack);
    });

Running it will produce output like this:

$ node validate-single-email.js greg@spam.netpirates.net
{ email: 'greg@spam.netpirates.net',
  validFormat: true,
  local: 'greg',
  domain: 'spam.netpirates.net',
  isDisposable: true,
  disposableDomains: [ 'mailinator.com' ],
  aliases: [ 'mailinator.com' ] }

1.6.4 Bulk Address Validation

The bulk address validation endpoint can be used to validate up to 50 email addresses at a time. Here is an example
script

1.6. Verifying Email Addresses                                                                                  13
mailsac-examples Documentation

const requestp = require('request-promise-native')

const MAILSAC_API_KEY = 'YOUR API KEY GOES HERE';
const addresses = process.argv.slice(2);

requestp.post(`https://mailsac.com/api/validations/addresses`, {
        json: true,
        body: {
            emails: addresses
        },
        headers: {
            'Mailsac-Key': MAILSAC_API_KEY
        },
    })
    .then((results) => {
        console.log(results);
    })
    .catch((err) => {
        console.error('Something broke!', err.message, err.stack);
    });

Running it will produce the following output:

$ node validate-multiple-emails.js greg@spam.netpirates.net jim@mailsac.com
[ { email: 'greg@spam.netpirates.net',
    validFormat: true,
    local: 'greg',
    domain: 'spam.netpirates.net',
    isDisposable: true,
    disposableDomains: [ 'mailinator.com' ],
    aliases: [ 'mailinator.com' ] },
  { email: 'jim@mailsac.com',
    validFormat: true,
    local: 'jim',
    domain: 'mailsac.com',
    isDisposable: true,
    disposableDomains: [ 'mailsac.com', 'sanstr.com', 'totalvista.com' ],
    aliases: [ 'mailsac.com', 'sanstr.com', 'totalvista.com', '45.76.28.175' ] } ]

1.7 Message Storage

Message storage defines how many messages can be stored before mail before messages are recycled. Messages that
are sent to a Custom Domain, Private Email Addresses, or starred messages count towards message storage.

1.7.1 When are Messages Recycled?

Messages sent to non-private addresses and domains will be recycled at times to ensure capacity for new messages.
Messages sent to private domains, private addresses, and starred messages associated with Mailsac are recycled once
the storage limit is reached.

14                                                                               Chapter 1. Table of Contents
mailsac-examples Documentation

1.7.2 Examples

   1. If your storage limit is 100 messages and you have starred 125 messages, the oldest 25 messages will be recycled.
   2. If your storage limit is 100 messages and you have 75 messages in your private domain. No messages will be
      recycled.
   3. If your storage limit is 100 messages and you have 150 messages in your private domain, the oldest 50 messages
      will be recycled.
   4. If your storage limit is 100 messages and you have 50 messages in 3 private inboxes (total 150 messages), the
      oldest 50 messages will be recycled.

1.7.3 Getting More Storage

Message storage can be purchased on a per-message basis in blocks listed on the pricing page.

1.7.4 Starred Messages

When you star a message, it counts towards your overall storage.
Use the star symbol
Your user Dashboard has links to all inboxes where you starred messages.
You can star messages on any address, including those you own or other public addresses.

1.7.5 Managing Storage

Most customers will never need to manage message storage, since emails are automatically recycled.
Messages can proactively be deleted:
       • Per message
       • Per private inbox
       • Per private domain

1.7.6 Delete a Message

REST API examples require the messageId parameter. messageId can be found using the List Inbox Email Mes-
sages Endpoint, a WebSocket Frame, and Webhook POST.
Mailsac Website

                                     Fig. 1: Delete message using the Mailsac Website

Unified Inbox

                              Fig. 2: Delete using the Unified Inbox (requires Private Address)

curl

1.7. Message Storage                                                                                                15
mailsac-examples Documentation

                              Listing 10: Delete using curl (requires messageId)
curl -s -H "Mailsac-Key: YOUR_API_KEY_HERE" \
     -X DELETE https://mailsac.com/api/addresses/bclinton@mailsac.com/messages/
 ˓→fkwhpdnzsQ81MdllcqfqCd3jQq-0

# curl output
{"message":"Message was deleted.","_id":"fkwhpdnzsQ81MdllcqfqCd3jQq-0","inbox":
 ˓→"bclinton@mailsac.com"}

Node.js Javascript

                     Listing 11: Delete message using Node.js. requires npm install
                     superagent
const superagent = require('superagent')
const mailsac_api_key = 'YOUR_API_KEY_HERE'
const messageId = 'YOUR_MESSAGE_ID'

superagent
   .delete('https://mailsac.com/api/addresses/bclinton@mailsac.com/messages/' +
 ˓→messageId)

   .set('Mailsac-Key', mailsac_api_key)
   .then((data) => {
       console.log(data.body)
   })
   .catch(err => {
       console.error(err.message);
   })

/*
{
     message: 'Message was deleted.',
     _id: 'sepjrPlPJsJEm6F8_cHeuCAcs-0',
     inbox: 'bclinton@mailsac.com'
}
*/

Python

16                                                                            Chapter 1. Table of Contents
mailsac-examples Documentation

                                     Listing 12: Read message using Python
import requests
from pprint import pprint

message_id = 'YOUR_MESSAGE_ID'
headers = {'Mailsac-Key': 'YOUR_API_KEY_HERE'}
url = 'https://mailsac.com/api/addresses/bclinton@mailsac.com/messages/' + message_id
r = requests.delete(url, headers=headers)
pprint(r.json())

'''
{'_id': '4xnxBtJpZxLQTU2MvcIPD65cdWQC-0',
 'inbox': 'bclinton@mailsac.com',
 'message': 'Message was deleted.'}
'''

1.7.7 Purge Inbox

Examples require the Inbox to be a Private Address
Mailsac Website

                                  Fig. 3: Purge inbox using the Mailsac Website

curl

                             Listing 13: Purge inbox using curl (requires messageId)
curl -s -H "Mailsac-Key: YOUR_API_KEY_HERE" \
    -X DELETE https://mailsac.com/api/addresses/bclinton@mailsac.com/messages

# Return Code 204 No Content

Node.js Javascript

                     Listing 14: Purge inbox using Node.js.       requires npm install
                     superagent
const superagent = require('superagent')
const mailsac_api_key = 'YOUR_API_KEY_HERE'

superagent
  .delete('https://mailsac.com/api/addresses/bclinton@mailsac.com/messages/')
  .set('Mailsac-Key', mailsac_api_key)
  .then((res) => {
      console.log(res.status)
  })
  .catch(err => {
      console.error(err.message);
  })

/*
204
*/

1.7. Message Storage                                                                                 17
mailsac-examples Documentation

Python

                                        Listing 15: Purge inbox using Python
import requests

headers = {'Mailsac-Key': 'YOUR_API_KEY_HERE'}
url = 'https://mailsac.com/api/addresses/bclinton@mailsac.com/messages'
r = requests.delete(url, headers=headers)
print(r.status_code)

'''
204
'''

1.7.8 Purge Domain

All messages in a verified domain can be deleted.
From the Dashboard, select Custom Domains, select manage next to the domain, click on the advanced tab, and click
on the button “Irreversibly Delete Emails”.

1.8 Email Attachments

For security, and to ensure the Mailsac website is not marked as a distributor of viruses, attachments are not publicly
accessible on the web.

1.8.1 Getting Attachments as Files

There are several ways to download attachments when authenticated to the Mailsac service

18                                                                                 Chapter 1. Table of Contents
mailsac-examples Documentation

   1. By clicking the Download button on any public message, you can open it locally in an email client and view the
      attachements.
   2. For private addresses, attachments can be downloaded in a web browser using the Unified Inbox app.
   3. Attachments can be downloaded using the MD5 hash of the attachment, using the common-attachments API.
   4. Attachments can be parsed out of the raw message using the API.
Additional information on reading mail, including code examples, can be found in Reading Email.

1.8.2 Sending Attachments

Attachments on outgoing messages are only supported through the API.
Additional information on sending mail, including code examples, can be found in Sending Email.

1.9 Email Hosting

Mailsac can host free disposable email for your existing custom domain. The email addresses and messages will be
public.
If you require a email messages to be private, or to setup forwarding of all emails received to single address, you can
subscribe for those services.

1.9.1 Configure Email Hosting

In your domain’s DNS configuration, you will need to create or modify the MX records (for public and private).

                                         Priority    Host    Value
                                         1           @       in.mailsac.com
                                         5           @       alt.mailsac.com

1.9.2 Common DNS Provider Links

                    DNS Provider          Documentation Link
                    Amazon Route 53       Creating Records Using the Amazon Route 53 Console
                    GoDaddy               Adding an MX record
                    Dreamhost             How do I change my MX records
                    Cloudflare            Managing DNS records in CloudFlare
                    HostGator             How to Setup Your MX Record
                    Namecheap             How can I setup mx records
                    Names.co.uk           Changing your domain’s DNS settings
                    Wix                   Adding or updating MX Records in Your Wix account

1.10 Webhook Forwarding

Emails sent to Private Email Addresses (or Catch-All addresses) can be forwarded to a URL also known as a webhook.

1.9. Email Hosting                                                                                                  19
mailsac-examples Documentation

1.10.1 Configure Webhook

Mailsac Website

Fig. 4: Select Manage Email Addresses from the Dashboard. Choose Settings next to the email address. In the Forward
to Custom Webhook setting enter the webhook address and select Save Settings

curl

                      Listing 16: Configure webhook forwarding on private address using curl
curl -H "Mailsac-Key: YOUR_API_KEY_HERE" \
     -H "Content-Type: application/json" \
     -X PUT https://mailsac.com/api/private-address-forwarding/bclinton@mailsac.com \
     --data '{"webhook": "https://mywebsite.com/webhooks"}'

# Curl Output
{
  "_id": "bclinton@mailsac.com",
  "owner": "mailsac_user",
  "forward": null,
  "enablews": false,
  "webhook": "https://mywebsite.com/webhooks",
  "webhookSlack": null,
  "webhookSlackToFrom": null,
  "catchAll": null,
  "password": null,
  "info": "",
  "created": "2020-08-19T23:31:15.664Z",
                                                                                               (continues on next page)

20                                                                               Chapter 1. Table of Contents
mailsac-examples Documentation

                                                                                     (continued from previous page)
     "updated": "2020-08-25T13:59:05.430Z"
}

Node.js Javascript

                     Listing 17: Configure webhook forwarding on a private address using
                     Node.js. requires npm install superagent
const superagent = require('superagent')

superagent
  .put('https://mailsac.com/api/private-address-forwarding/bclinton@mailsac.com')
  .set('Mailsac-Key', 'YOUR_API_KEY_HERE')
  .send({
      webhook: "https://mywebsite.com/webhooks"
  })
  .then((res) => {
      console.log(res.body)
  })
  .catch(err => {
      console.log(err.message)
  })

     /*
     { _id: 'bclinton@mailsac.com',
     owner: 'mailsac_user',
     forward: null,
     enablews: false,
     webhook: 'https://mywebsite.com/webhooks',
     webhookSlack: null,
     webhookSlackToFrom: null,
     catchAll: null,
     password: null,
     info: '',
     created: '2020-08-19T23:31:15.664Z',
     updated: '2020-08-25T14:04:34.261Z' }
*/

Python

                     Listing 18: Configure webhook forwarding on a private address using
                     Python.
import requests
from pprint import pprint

headers = {'Mailsac-Key': 'YOUR_API_KEY_HERE'}
url = 'https://mailsac.com/api/private-address-forwarding/bclinton@mailsac.com'
data = { 'webhook':'https://mywebsite.com/webhooks' }

r = requests.put(url, data=data, headers=headers)
pprint(r.json())
'''
{'_id': 'bclinton@mailsac.com',
 'catchAll': None,
 'created': '2020-08-19T23:31:15.664Z',
                                                                                           (continues on next page)

1.10. Webhook Forwarding                                                                                       21
mailsac-examples Documentation

                                                                                (continued from previous page)
 'enablews': False,
 'forward': None,
 'info': '',
 'owner': 'mailsac_user',
 'password': None,
 'updated': '2020-08-25T14:11:14.695Z',
 'webhook': 'https://mywebsite.com/webhooks',
 'webhookSlack': None,
 'webhookSlackToFrom': None}
 '''

1.10.2 Webhook Sample JSON

This is an example of the JSON that will be passed to the Webhook URL.

{"text": "this is a message",
"headers": {
      "dkim-signature": "redacted",
      "received": "2017-05-01T05:22:03.000Z",
      "content-type": "text/plain",
      "from": "mastadon@mailsac.com",
      "to": "gemini@mailsac.com",
      "subject": "",
      "message-id": "",
      "list-unsubscribe": "",
      "content-transfer-encoding": "7bit",
      "date": "Wed, 1 May 2017 05:22:03 +0000",
      "mime-version": "1.0"
},
"subject": "twin",
"messageId": "MS-5412430010104145004240335343@mailsac.com",
"priority": "normal",
"from": [{
      "address": "mastadon@mailsac.com",
      "name": ""
}],
"to": [{
      "address": "gemini@mailsac.com",
      "name": ""
}],
"date": "2017-05-01T05:22:03.000Z",
"receivedDate": "2017-05-01T05:22:03.000Z",
"originalInbox": "gemini@mailsac.com",
"inbox": "gemini@mailsac.com",
"domain": "mailsac.com",
"encryptedInbox": "inbox-db54b7f5f09041165aaaaae5ca9557c806cf3d95f8",
"raw": "DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=mailsac.com;\r\n
 ˓→q=dns/txt; s=mailsacrelay;\r\n bh=redacted;\r\n h=from:subject:to:mime-

 ˓→version:content-type:content-transfer-encoding:list-unsubscribe;\r\n

 ˓→b=redacted\r\nReceived: from localhost (127.0.0.1) by mailer with SMTP; Wed May

 ˓→1\r\n 2017 01:22:03 GMT-0400 (EDT)\r\nContent-Type: text/plain\r\nFrom:

 ˓→mastadon@mailsac.com\r\nTo: gemini@mailsac.com\r\nSubject: twin\r\nMessage-ID:\r\n

 ˓→\r\nList-Unsubscribe: \r\nContent-Transfer-Encoding: 7bit\r\nDate: Wed, 1 May 2017

 ˓→05:22:03 +0000\r\nMIME-Version: 1.0\r\n\r\this is a message",

"received": "2017-05-01T05:22:04.851Z",
                                                                                      (continues on next page)

22                                                                       Chapter 1. Table of Contents
mailsac-examples Documentation

                                                                                            (continued from previous page)
"_id": "IhnBcuaaiC",
"ip": "127.0.0.1"
}

Webhook contents are very similar to web socket emails.
Read more about JSON Webhooks at the API Reference

1.10.3 Troubleshooting

If the Webhook forwarding is not working, additional debugging information is available in Recent Activity.

1.11 WebSocket

A Websocket provides a unique way of monitoring the incoming email of a particular address. With a single persistent
connection all content from an email address can be forward over the Websocket. This allows your application to be
notified of an incoming emails as soon as it arrives. This helps reduce the number of API calls and reduces latency
from when the email arrives and your application responds to it.
Want to see it in action? The WebSocket Test Page allows you to show how it works with no programming involved.

Tip: You will need an API key and a private address or custom domain.

1.11.1 Configure Private Address for WebSocket

To use the Websocket feature a private email is required. Private addresses can be purchased individually as part of a
API Developer Subscription.

Option 1: Reserve Private Address via API

The REST API is the easiest way to reserve a private address.
A simple HTTP POST will do. Make sure you have private address credits already, from a paid plan or addon purchase.
user1@mailsac.com in the example should be replaced with the email address you wish to reserve. If you use a
custom domain, different than mailsac.com, you must have the domain configured with DNS records to delivery mail
to Mailsac.

curl -X POST -H "Mailsac-Key: YOUR_API_KEY_HERE" https://mailsac.com/api/addresses/
 ˓→user1@mailsac.com

Next, configure the private address for web socket publishing:

curl -H 'Mailsac-Key: YOUR_API_KEY_HERE' -X PUT https://mailsac.com/api/private-
 ˓→address-forwarding/user1@mailsac.com -d '{"enablews": true}'

1.11. WebSocket                                                                                                       23
mailsac-examples Documentation

Option 2: Reserve Private Address in the Dashboard

     1. Sign in to your Mailsac account.
     2. Select Manage Email Addresses from the dropdown.

     3. Select Add Email Address from Manage Email Addresses

     4. Fill in the desired email address and optionally add a note.

24                                                                     Chapter 1. Table of Contents
mailsac-examples Documentation

   5. Select Manage Email Addresses and choose settings next to the email address you want to configure for Web-
      socket.

   6. Check the box to “Forward all incoming emails via web socket”

1.11.2 Receive Mail Using a WebSocket

Receiving mail from a Websocket allows for interacting with incoming email in near real time.
WebSockets are a powerful tool allowing you to end-to-end test your application’s email delivery systems, or respond
to incoming mail in sophisticated ways - without having to setup a mail server or mess around with SMTP code.

Prerequsites

    • Mailsac API Key
    • Node.js and npm
    • Private email address with websocket configured

Setup

1.11. WebSocket                                                                                                  25
mailsac-examples Documentation

                            Listing 19: Create directory for example code
$ mkdir websocket-example
$ cd websocket-example

                    Listing 20: Create package.json file with the following contents
{
    "name": "mailsac-node-websocket-example",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "MIT",
    "dependencies": {
      "ws": "^2.2.3"
    }

                              Listing 21: Install required node packages
npm install

                     Listing 22: Create example.js file with the following contents
const WebSocket = require('ws');
const log = console.log; // eslint-disable-line

// Mailsac uses secure WebSockets. This is the WebSocket API base endpoint.
const BASE_URL = 'wss://sock.mailsac.com/incoming-messages';

// In this example, we pull the username and API key from environment variables.
// You could also hardcode the credentials, or use a package like node-config for
 ˓→managing them.

const username = process.env.MAILSAC_USER;
const apiKey = process.env.MAILSAC_KEY;
// List the addresses you want to receive messages for.
// You MUST have WebSocket forwarding turned on for the addresses!
const listenAddresses = process.env.ADDRESSES;

const urlParams = '?_id=' + username + '&key=' +apiKey+ '&addresses=' +
 ˓→listenAddresses;

log('attempting to open WebSocket to', BASE_URL + urlParams);
const ws = new WebSocket(BASE_URL + urlParams);

ws.on('open', function () {
  log('WebSocket opened');
});

ws.on('error', function (err) {
  log('connection error', err);
});
                                                                                        (continues on next page)

26                                                                          Chapter 1. Table of Contents
mailsac-examples Documentation

                                                                                     (continued from previous page)

ws.on('message', function (data) {
  log(data);
});

                                   Listing 23: Set environmental variables
export MAILSAC_USER='your mailsac username / _id';
export MAILSAC_KEY='your mailsac api key';
export ADDRESSES='myaddress@mailsac.com,some-address@example.com'

Launch WebSocket Example

                                    Listing 24: Launch the node program
node example.js

                                        Listing 25: Expected output
attempting to open WebSocket to wss://sock.mailsac.com/incoming-messages?_id=username&
 ˓→key=apikey&addresses=user1@mailsac.com

WebSocket opened
{"status":200,"msg":"Listening","addresses":["user1@mailsac.com"]}

Now, when an email messages are delivered to user1@mailsac.com, they will also be sent to your WebSocket. Try
sending a message - it will be parsed into JSON and logged to the console.

                           Listing 26: Example message received over WebSocket
{
   "_id": "8mryf3viZQpWLX7E8SUzI3a5rEwg-0",
   "to": [
     {
       "address": "user1@mailsac.com",
       "name": ""
     }
   ],
   "from": [
     {
       "address": "from_test@mailsac.com",
       "name": ""
     }
   ],
   "subject": "This is a subject",
   "inbox": "user1@mailsac.com",
   "originalInbox": "user1@mailsac.com",
   "domain": "mailsac.com",
   "received": "2020-06-23T01:33:13.790Z",
   "raw": "Received: from 0.0.0.0 by frontend1-172-31-29-224 via 172.31.42.57 with
 ˓→HTTP id 8ml9bOrEQ7J_0VMd0vjPULgc for ; Tue Jun 23 2020 01:33:13 GMT+0000

 ˓→(Coordinated Universal Time)\nReceived: from 0.0.0.0\n\tsmtp-in2-172-31-42-57 via

 ˓→172.31.23.10 (proxy)\n\twith SMTP id 8ml9bOrEQ7J_0VMd0vjPULgc\n\tfor ; Tue, 23 Jun

 ˓→2020 01:33:13 UTC\nX-Mailsac-Whitelist: user1@mailsac.com,from_test@mailsac.com,0.0.

 ˓→0.0\nX-Mailsac-Inbound-Version: 7463aab\nDKIM-Signature: v=1; a=rsa-sha256;

 ˓→c=relaxed/relaxed; d=mailsac.com;\n q=dns/txt; s=mailsacrelay;\n      (continues on next page)
 ˓→bh=r0Rk73qDq89EuDZsfA4VqbZ/rqPclpo6FwUp6HTtsgg=;\n h=from:subject:to:mime-

 ˓→version:content-type:list-unsubscribe;\n b=C7leDzbCghwRfubINLbVmzTiecO/

1.11.  WebSocket
 ˓→nA7zEsX0xuFJ9D8om617iGcD6q7CGysMu8jXcohxeeINI\n                                            27
 ˓→i2GvfKq2L7sXNPPFwBsnjGvIL8mJQYHWI+FEG3+TCnTc7ZRavKmQPAJl3B2k9QroWp5s2RyCdpJ\n

 ˓→vX+qjcoo7zwld6R2+C6Kmz4=\nContent-Type: multipart/alternative;\n boundary=\"----

 ˓→sinikael-?=_1-15928759930350.8681360034141601\"\nReceived: from frontend1-172-31-29-
mailsac-examples Documentation

                                                                                            (continued from previous page)
   "size": 1697,
   "rtls": true,
   "ip": "0.0.0.0",
   "spam": 0.014,
   "headers": {
     "received": [
        "from 0.0.0.0 by frontend1-172-31-29-224 via 172.31.42.57 with HTTP id
 ˓→8ml9bOrEQ7J_0VMd0vjPULgc for ; Tue Jun 23 2020 01:33:13 GMT+0000 (Coordinated

 ˓→Universal Time)",

        "from 0.0.0.0 smtp-in2-172-31-42-57 via 172.31.23.10 (proxy) with SMTP id
 ˓→8ml9bOrEQ7J_0VMd0vjPULgc for ; Tue, 23 Jun 2020 01:33:13 UTC",

        "from frontend1-172-31-29-224 ([0.0.0.0]) with HTTP by cranberry; Mon Jun 22
 ˓→2020 21:33:12 GMT-0400 (Eastern Daylight Time)",

        "from ruffrey (from_test@mailsac.com) ([0.0.0.0]) with HTTP id fe-vlp0jxneoa8
 ˓→by frontend1-172-31-29-224 ([0.0.0.0]); 2020-06-23T01:33:12.177Z"

     ],
     "x-mailsac-whitelist": "user1@mailsac.com,from_test@mailsac.com,0.0.0.0",
     "x-mailsac-inbound-version": "7463aab",
     "dkim-signature": "v=1; a=rsa-sha256; c=relaxed/relaxed; d=mailsac.com; q=dns/txt;
 ˓→ s=mailsacrelay; bh=r0Rk73qDq89EuDZsfA4VqbZ/rqPclpo6FwUp6HTtsgg=;

 ˓→h=from:subject:to:mime-version:content-type:list-unsubscribe;

 ˓→b=C7leDzbCghwRfubINLbVmzTiecO/nA7zEsX0xuFJ9D8om617iGcD6q7CGysMu8jXcohxeeINI

 ˓→i2GvfKq2L7sXNPPFwBsnjGvIL8mJQYHWI+FEG3+TCnTc7ZRavKmQPAJl3B2k9QroWp5s2RyCdpJ

 ˓→vX+qjcoo7zwld6R2+C6Kmz4=",

     "content-type": "multipart/alternative; boundary=\"----sinikael-?=_1-
 ˓→15928759930350.8681360034141601\"",

     "from": "from_test@mailsac.com",
     "to": "jeff@mailsac.com",
     "subject": "This is a subject",
     "message-id": "",
     "list-unsubscribe": "",
     "date": "Tue, 23 Jun 2020 01:33:13 +0000",
     "mime-version": "1.0"
   },
   "text": "Here's some message text.\n\nWe are testing web sockets.\n",
   "html": "Here's some message text.\n\nWe are testing web sockets.\n",
   "via": "172.31.42.57"
}

The WebSocket message body is nearly identical to the Messages REST API with the addition of the key “raw” which
contains the entire raw email message received over SMTP.

Try It

Visit the Web Socket Test Page and receive emails in your web browser, without writing any code.

1.11.3 Troubleshooting

If the WebSocket is not working, additional debugging information is available in Recent Activity.

28                                                                                Chapter 1. Table of Contents
mailsac-examples Documentation

1.12 Email Forwarding Overview

Forwarding, or routing, allows email to be sent on to a further email address or service (Webhook, WebSocket, Slack
Webhook). Private addresses and custom domains can be configured for email forwarding. Forwarding is not available
on disposable email addresss.

1.12.1 Catch-All Domain Forwarding Addresses

A Catch-All email address can receive all the mail for a custom domain, and optionally forward it to another ad-
dress or service ( Webhook, WebSocket, or Slack Webhook). A Catch-All address is a private address in the format
*@example.com.
A Catch-All email address can be configured by selecting Manage Domains from the Dashboard, then choosing
Manage next to the domain, then selecting the Forwarding tab, and toggling the Enable Catch-All.

                               Fig. 5: Enable Catch-All address on custom domain.

Configure Forwarding on a Catch-All Address

Catch-All addresses can be forwarded to:
    • Another Private Mailsac Address
    • Slack
    • Webhook
    • WebSocket
From the Dashboard, select Manage Email Addresses, then select settings icon next to the Catch-All address.

Catch-All Example Use Case

Traditionally individual mailboxes need to be configured for each address in a domain. If a small business wants to
add a new address, sales@widgets.com, they would need to configure that mailbox. With a Catch-All address they
can instruct customers to start sending to sales@widgets.com and all the messages sent to sales@widgets.com will be
forwarded to the Catch-All (*@widgets.com).
Catch-All forwarding makes adding a new email address as simple as sending to it.

1.12. Email Forwarding Overview                                                                                 29
mailsac-examples Documentation

                                Fig. 6: Configure Forwarding on a Catch-All Address

1.12.2 Forward to Another Mailsac Address

Any private address, in the @mailsac.com domain or private domain can be forwarded to another private address. This
allows you to consolidate many email addresses into a single inbox.
Forwarding to another private address can be configured by selecting Manage Email Addresses from the Dashboard.
Select the Settings button next to the email address to manage, then choose the private address to forward to from the
Forward to Another Email Address dropdown and select Save Settings
For example, if you own 1@mailsac.com, 2@mailsac.com, 3@mailsac.com, and main@mailsac.com, you could setup
the following scheme:
     • 1@mailsac.com forwards to main@mailsac.com
     • 2@mailsac.com forwards to main@mailsac.com
     • 3@mailsac.com forwards to main@mailsac.com
     • main@mailsac.com is checked by POP3 in GMail

1.12.3 Forward to Slack

Emails sent to a private address or Catch-All can be forwarded to a Slack Channel.
Slack forwarding requires a private address to be configured, but this can be a custom domain with a Catch-All private
address (included with a verified custom domain).
Forwarding to Slack can be configured by selecting Manage Email Addresses from the Dashboard. Select the Settings
button next to the email address to manage, then input the Slack Webhook URL and select Save Settings. Step-by-Step
instructions are provided.

1.12.4 Forward to Webhook

Private addresses and Catch-All addresses can have their mail forwarded to a webhook. Configuration of the webhook
only requires a destination URL.

30                                                                                   Chapter 1. Table of Contents
mailsac-examples Documentation

Forwarding to a Webhook can be configured by selecting Manage Email Addresses from the Dashboard. Select the
Settings button next to the email address to manage, then input the URL under Forward To Custom Webhook and select
Save Settings.

1.12.5 WebSocket Forwarding

Private addresses and Catch-All addresses can have their mail forwarded to a WebSocket. A WebSocket uses a single
persistent connection to notify a WebSocket client as soon as a message arrives. The WebSocket Test Page demon-
strates a WebSocket.
Forwarding to a WebSocket can be configured by selecting Manage Email Addresses from the Dashboard. Select the
Settings button next to the email address to manage, then check the box labeled Enable forwarding all incoming email
via web socket, and select Save Settings.
A code example for a WebSocket is available available.
Additional information about the WebSocket endpoint, authentication and example frame format is show in the API
Documentation.

1.13 Sending Email

Email can be sent via the following methods:
       • Web Form
       • Unified Inbox
       • REST API
       • SMTP

1.13.1 Send an Email Message

Mailsac Website
Unified Inbox
curl

                                            Listing 27: Send using curl
curl -H "Mailsac-Key: YOUR_API_KEY_HERE" -X POST \
https://mailsac.com/api/outgoing-messages \
-H "Content-Type: application/json" --data '{ "to":"myfriend@mailsac.com", "from":
 ˓→"user1@mailsac.com", "subject": "Hello Myfriend", "text": "test message from mailsac

 ˓→" }'

# Response
{
  "from": "user1@mailsac.com",
  "to": [
    "myfriend@mailsac.com"
  ],
  "id": "fe-3hl55xcrzgr"
}

Node.js Javascript

1.13. Sending Email                                                                                              31
mailsac-examples Documentation

                          Fig. 7: Send using the Compose Message Form

                                 Fig. 8: Send using the Unified Inbox

32                                                                      Chapter 1. Table of Contents
mailsac-examples Documentation

                     Listing 28: Send using Node.js.           requires npm install
                     superagent
const superagent = require('superagent')

superagent
  .post('https://mailsac.com/api/outgoing-messages')
  .set('Mailsac-Key', 'YOUR_API_KEY_HERE')
  .send({
      to: "myfriend@mailsac.com",
      from: "user1@mailsac.com",
      subject: "Hello Myfriend",
      text: "test message from mailsac"
  })
  .then((res) => {
      console.log(res.body)
  })
  .catch(err => {
      console.log(err.message)
  })

     /*
     {
     from: 'user1@mailsac.com',
     to: [ 'myfriend@mailsac.com' ],
     id: 'fe-ipic46bqge8'
}
*/

Python

                                        Listing 29: Send using Python
import requests
from pprint import pprint

headers = {'Mailsac-Key': 'YOUR_API_KEY_HERE'}
url = 'https://mailsac.com/api/outgoing-messages'
mail = { 'to':'myfriend@mailsac.com',
         'from':'user1@mailsac.com',
         'subject':'Hello Myfriend',
         'text': 'mailsac allows for sending of email'
       }

r = requests.post(url, data=mail, headers=headers)
pprint(r.json())
'''
{'from': 'user1@mailsac.com',
 'id': 'fe-tgitrk8dbga',
 'to': ['myfriend@mailsac.com']}
'''

1.13.2 Allowed from addresses

The from address must be a Private Address or an address within a Custom Domains.

1.13. Sending Email                                                                                 33
mailsac-examples Documentation

1.13.3 Sending credits

Sending Email, both replies and new messages, is available only from private addresses and private domains. Sending
or replying requires mail credits.

1.13.4 Sent Messages Are Not Saved

Outgoing messages are not saved. They may be visible or cached temporarily by our outgoing mail services, and
logged in debugging messages on Mailsac servers, but not explicitly archived by Mailsac at this time.

1.13.5 Sending from the API

The REST API is the preferred method for sending messages programmattically. The /api-outgoing-messages
endpoint is documented in the REST API documentation.
     1. Generate an API by selecting API Keys from the Dashboard.
     2. Send email using curl or your favorite HTTP library. Code Examples

1.13.6 Sending with SMTP

Sending via SMTP allows email clients to send email using Mailsac.
Authentication
SMTP uses a username and password for authentication. The API key for your account can be used to send from
any of your private addresses or domains. Alternatively, you can use a per private address SMTP password. The per
private address SMTP password can be set through using the Dashboard -> Manage Email Addresses -> Select the
POP/SMTP button next to the email address -> Select Set New Password

Email Client Configuration
Configure your email client (Gmail, Apple mail, Thunberbird, Outlook, iPhone, etc) using these SMTP settings:

34                                                                               Chapter 1. Table of Contents
mailsac-examples Documentation

                                 Hostname / Server     out.mailsac.com
                                 Email Address         Private email address
                                 Username              Private email address

                                 Password              API Key or SMTP Key
                                 Port                  587
                                 Auth Settings         Password / allow plain / insecure
                                 Encryption            TLS

To configure a mail client for reading see the Reading Mail via POP3 Section.

1.13.7 Internal SMTP Sending

For plans with unlimited internal sending messages can be sent through Mailsac’s outbound SMTP server
(out.mailsac.com). Any messages sent to a Mailsac hosted domain will not require sending credits.

                      Hostname / Server    out.mailsac.com
                      Email Address        Private email address or email address in a private domain
                      Username             Private email address or email address in a private domain

                      Password             API Key
                      Port                 587
                      Auth Settings        Password / allow plain / insecure
                      Encryption           TLS

1.14 Reading Email

There are several ways for to view email messages using Mailsac
       • Inbox View
       • Unified Inbox
       • REST API
       • POP3

1.14.1 Read an Email Message

Mailsac Website

                             Fig. 9: View Emails from the main page of the Mailsac Website

Unified Inbox

                                          Fig. 10: Read using the Unified Inbox

curl

1.14. Reading Email                                                                                        35
You can also read