# Emails (Secure Links)

Send a secure email link for a document. Useful when you want recipients to access PHI via a time-limited link.

## Send Secure Link

POST `/emails` — Sends a secure email link for a document.

Request Parameters (multipart form data)

| Parameter | Required | Description |
| --- | --- | --- |
| file | Yes | PDF or TIFF document to share |
| recipient_email | Yes | Email address of the recipient |
| recipient_name | No | Name of the recipient (displayed in email) |
| sender_name | No | Name of the sender (displayed in email) |
| reply_to_email | No | Reply-to email address |
| subject | No | Email subject line |
| note | No | Internal note for your reference |
| patient_name | No | Patient name for record keeping |
| patient_dob | No | Patient date of birth (YYYY-MM-DD) |
| expire_after | No | Days until link expires (1-180, default 30) |
| callback_url | No | URL to receive status callback |

#### cURL

```bash
export API_BASE="https://api.medsender.com/api/v2"
export API_KEY="sk_test_..."

curl -s -X POST -H "Authorization: Bearer $API_KEY" \
  -F "file=@./sample.pdf" \
  -F "recipient_email=recipient@example.com" \
  -F "recipient_name=Recipient" \
  -F "sender_name=Sender" \
  -F "subject=Secure Link" \
  -F "note=Referral" \
  -F "expire_after=30" \
  -F "callback_url=https://example.com/webhooks/email" \
  "$API_BASE/emails"
```

#### Node

```javascript
import { readFile } from 'fs/promises';

const API_BASE = 'https://api.medsender.com/api/v2';
const API_KEY = 'sk_test_...';
const fd = new FormData();
const fileBuffer = await readFile('./sample.pdf');
fd.append('file', new Blob([fileBuffer]), 'sample.pdf');
fd.append('recipient_email', 'recipient@example.com');
fd.append('recipient_name', 'Recipient');
fd.append('sender_name', 'Sender');
fd.append('subject', 'Secure Link');
fd.append('note', 'Referral');
fd.append('expire_after', '30');
fd.append('callback_url', 'https://example.com/webhooks/email');
const res = await fetch(`${API_BASE}/emails`, { method: 'POST', headers: { Authorization: `Bearer ${API_KEY}` }, body: fd });
console.log(await res.json());
```

#### TypeScript

```typescript
const API_BASE: string='https://api.medsender.com/api/v2';
const API_KEY: string='sk_test_...';
const fd = new FormData();
fd.append('file', new Blob([await (await fetch('./sample.pdf')).arrayBuffer()]), 'sample.pdf');
fd.append('recipient_email','recipient@example.com');
fd.append('recipient_name','Recipient');
fd.append('sender_name','Sender');
fd.append('subject','Secure Link');
const res = await fetch(`${API_BASE}/emails`, { method:'POST', headers:{ Authorization: `Bearer ${API_KEY}` }, body: fd });
console.log(await res.json());
```

#### Python

```python
import requests
API_BASE='https://api.medsender.com/api/v2'
API_KEY='sk_test_...'
files={'file':open('./sample.pdf','rb')}
data={
  'recipient_email':'recipient@example.com',
  'recipient_name':'Recipient',
  'sender_name':'Sender',
  'subject':'Secure Link',
  'note':'Referral',
  'expire_after':'30',
  'callback_url':'https://example.com/webhooks/email'
}
r=requests.post(f"{API_BASE}/emails",headers={'Authorization':f'Bearer {API_KEY}'},files=files,data=data)
print(r.json())
```

#### Ruby

```ruby
require 'net/http'
require 'uri'
uri = URI.parse('https://api.medsender.com/api/v2/emails')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = 'Bearer sk_test_...'
form = [ ['file', File.open('sample.pdf')], ['recipient_email','recipient@example.com'], ['sender_name','Sender'] ]
request.set_form(form, 'multipart/form-data')
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true){|http| http.request(request)}
puts res.body
```

#### PHP

```php
<?php
$ch = curl_init();
$post = [
  'file' => new CURLFile('sample.pdf', 'application/pdf', 'sample.pdf'),
  'recipient_email' => 'recipient@example.com',
  'sender_name' => 'Sender'
];
curl_setopt_array($ch, [
  CURLOPT_URL => 'https://api.medsender.com/api/v2/emails',
  CURLOPT_POST => true,
  CURLOPT_HTTPHEADER => ['Authorization: Bearer sk_test_...'],
  CURLOPT_POSTFIELDS => $post,
  CURLOPT_RETURNTRANSFER => true
]);
$res = curl_exec($ch);
echo $res;
```

#### Java

```java
import java.net.http.*;
import java.net.URI;
import java.nio.file.*;
import java.util.*;

public class EmailSend {
  public static void main(String[] args) throws Exception {
    var boundary = UUID.randomUUID().toString();
    var client = HttpClient.newHttpClient();

    // Build multipart body
    var fileBytes = Files.readAllBytes(Path.of("sample.pdf"));
    var body = new StringBuilder();
    body.append("--").append(boundary).append("\r\n");
    body.append("Content-Disposition: form-data; name=\"file\"; filename=\"sample.pdf\"\r\n");
    body.append("Content-Type: application/pdf\r\n\r\n");
    var prefix = body.toString().getBytes();
    var suffix = ("\r\n--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"recipient_email\"\r\n\r\nrecipient@example.com\r\n--" + boundary + "\r\n" +
      "Content-Disposition: form-data; name=\"sender_name\"\r\n\r\nSender\r\n--" + boundary + "--\r\n").getBytes();

    var fullBody = new byte[prefix.length + fileBytes.length + suffix.length];
    System.arraycopy(prefix, 0, fullBody, 0, prefix.length);
    System.arraycopy(fileBytes, 0, fullBody, prefix.length, fileBytes.length);
    System.arraycopy(suffix, 0, fullBody, prefix.length + fileBytes.length, suffix.length);

    var req = HttpRequest.newBuilder()
      .uri(URI.create("https://api.medsender.com/api/v2/emails"))
      .header("Authorization", "Bearer sk_test_...")
      .header("Content-Type", "multipart/form-data; boundary=" + boundary)
      .POST(HttpRequest.BodyPublishers.ofByteArray(fullBody))
      .build();
    var res = client.send(req, HttpResponse.BodyHandlers.ofString());
    System.out.println(res.body());
  }
}
```

#### C#

```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
var api = "https://api.medsender.com/api/v2/emails";
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer sk_test_...");
using var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(System.IO.File.ReadAllBytes("sample.pdf")), "file", "sample.pdf");
form.Add(new StringContent("recipient@example.com"), "recipient_email");
form.Add(new StringContent("Sender"), "sender_name");
var res = await client.PostAsync(api, form);
Console.WriteLine(await res.Content.ReadAsStringAsync());
```

Response

```json
{
  "message": "Record has been sent, we will send a callback upon completion.",
  "email_id": "e5f6a7b8c9d0"
}
```

## Get Email

GET `/emails/:id` — Retrieves details for a specific secure link email.

The `:id` parameter is the `email_id` returned when you created the email.

#### cURL

```bash
curl -s -H "Authorization: Bearer sk_test_..." "https://api.medsender.com/api/v2/emails/REPLACE_EMAIL_ID" | jq
```

#### Node

```javascript
const API_BASE='https://api.medsender.com/api/v2';
const API_KEY='sk_test_...';
const id='REPLACE_EMAIL_ID';
const res=await fetch(`${API_BASE}/emails/${id}`,{headers:{Authorization:`Bearer ${API_KEY}`}});
console.log(await res.json());
```

#### TypeScript

```typescript
const API_BASE: string='https://api.medsender.com/api/v2';
const API_KEY: string='sk_test_...';
const id: string='REPLACE_EMAIL_ID';
const res = await fetch(`${API_BASE}/emails/${id}`, { headers: { Authorization: `Bearer ${API_KEY}` } });
console.log(await res.json());
```

#### Python

```python
import requests
API_BASE='https://api.medsender.com/api/v2'
API_KEY='sk_test_...'
id='REPLACE_EMAIL_ID'
r=requests.get(f"{API_BASE}/emails/{id}", headers={'Authorization':f'Bearer {API_KEY}'})
print(r.json())
```

#### Ruby

```ruby
require 'net/http'
require 'uri'
id = 'REPLACE_EMAIL_ID'
uri = URI.parse("https://api.medsender.com/api/v2/emails/#{id}")
req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer sk_test_...'
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true){|http| http.request(req)}
puts res.body
```

#### PHP

```php
<?php
$id = 'REPLACE_EMAIL_ID';
$ch = curl_init();
curl_setopt_array($ch, [
  CURLOPT_URL => 'https://api.medsender.com/api/v2/emails/' . $id,
  CURLOPT_HTTPHEADER => ['Authorization: Bearer sk_test_...'],
  CURLOPT_RETURNTRANSFER => true
]);
$res = curl_exec($ch);
echo $res;
```

#### Java

```java
import java.net.http.*;
import java.net.URI;
public class GetEmail {
  public static void main(String[] args) throws Exception {
    var id = "REPLACE_EMAIL_ID";
    var client = HttpClient.newHttpClient();
    var req = HttpRequest.newBuilder()
      .uri(URI.create("https://api.medsender.com/api/v2/emails/" + id))
      .header("Authorization","Bearer sk_test_...")
      .GET()
      .build();
    var res = client.send(req, HttpResponse.BodyHandlers.ofString());
    System.out.println(res.body());
  }
}
```

#### C#

```csharp
using System;
using System.Net.Http;
var id = "REPLACE_EMAIL_ID";
var url = "https://api.medsender.com/api/v2/emails/" + id;
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization","Bearer sk_test_...");
var res = await client.GetAsync(url);
Console.WriteLine(await res.Content.ReadAsStringAsync());
```

Response

```json
{
  "sender_name": "Example Provider",
  "recipient_email": "recipient@example.com",
  "recipient_name": "Dr. Example",
  "reply_to_email": null,
  "patient_name": "John Doe",
  "patient_dob": "1990-01-15",
  "record_status": "activated",
  "email_status": "success",
  "email_id": "e5f6a7b8c9d0",
  "secure_link": "https://records.medsender.com/...",
  "expiry": "2025-02-15T10:00:00.000Z",
  "sent_at": "2025-01-15T10:00:00.000Z",
  "note": "Referral documents",
  "subject": "Secure Medical Documents",
  "last_viewed_at": null,
  "is_test": false,
  "error_details": {
    "error_code": null,
    "error_details": null
  }
}
```

Response Fields

| Field | Description |
| --- | --- |
| email_id | Unique identifier for this email (use to retrieve status) |
| recipient_email | Email address the link was sent to |
| recipient_name | Recipient name if provided |
| sender_name | Sender name if provided |
| reply_to_email | Reply-to email address if provided |
| subject | Email subject line |
| note | Internal note if provided |
| patient_name | Patient name if provided |
| patient_dob | Patient date of birth if provided |
| record_status | Status: "activated", "archived", or "revoked" |
| email_status | Delivery status: "queued", "inprogress", "success", or "failure" |
| secure_link | The secure URL to view the document |
| expiry | When the secure link expires (ISO 8601) |
| sent_at | When the email was sent (ISO 8601) |
| last_viewed_at | When the link was last viewed, or null |
| is_test | Whether this was sent using test credentials |
| error_details | Error information if email_status is "failure" |
