# Invoice Sending

Configure how invoices are sent to customers using different channels and scheduling options. This section covers send configuration, status tracking, and delivery channels.

## Overview

When creating an invoice, you can add an optional `Send` node to control how and when the invoice is delivered to the customer. This allows you to override default sending behavior and use specific channels or scheduling.

## Send Configuration

### Basic Send Properties

| Property           | Type     | Description              | Values                         |
| ------------------ | -------- | ------------------------ | ------------------------------ |
| `Channel`          | string   | Delivery channel         | `sms`, `email`, `xml`, `print` |
| `Status`           | string   | Send status              | `Queue` (only valid value)     |
| `ToAddress`        | string   | Delivery address         | Varies by channel              |
| `ScheduleSendDate` | DateTime | Scheduled send date/time | YYYY-MM-DD HH:MM               |
| `Note`             | string   | Additional message       | Custom text                    |

### Channel-Specific Address Formats

| Channel   | Address Format | Example                |
| --------- | -------------- | ---------------------- |
| **SMS**   | Phone number   | `+4533445566`          |
| **Email** | Email address  | `customer@example.com` |
| **XML**   | GLN number     | `5790000123456`        |
| **Print** | Not required   | (empty)                |

## Send Examples

### SMS Delivery

```json
{
  "Channel": "SMS",
  "Status": "Queue",
  "ToAddress": "+4533445566",
  "ScheduleSendDate": "2024-05-31 15:55",
  "Note": "Here is your invoice - Cheers!"
}
```

### Email Delivery

```json
{
  "Channel": "Email",
  "Status": "Queue",
  "ToAddress": "customer@example.com",
  "ScheduleSendDate": "2024-05-31 10:00",
  "Note": "Please find your invoice attached. Thank you for your business!"
}
```

### XML Delivery (E-boks)

```json
{
  "Channel": "XML",
  "Status": "Queue",
  "ToAddress": "5790000123456",
  "ScheduleSendDate": "2024-05-31 09:00"
}
```

### Print Delivery

```json
{
  "Channel": "Print",
  "Status": "Queue",
  "ScheduleSendDate": "2024-05-31 08:00"
}
```

## Send Status Tracking

### Status Values and Meanings

| Status                | Value | Description                                                              |
| --------------------- | ----- | ------------------------------------------------------------------------ |
| `Queue`               | 100   | Invoice has just been created, not handled by FarPay yet                 |
| `PendingApproval`     | 110   | Future states for invoices with approval workflow                        |
| `ReadyToPrint`        | 150   | Invoice is placed in print queue (due to configuration or missing email) |
| `Sent`                | 200   | Invoice has been sent successfully                                       |
| `Error`               | 300   | Invoice is halted and will not be processed                              |
| `ErrorSendingEmail`   | 310   | Technical issues (e.g., bad SMTP connection)                             |
| `WrongEmailAddress`   | 320   | No mailbox found with that email address                                 |
| `EmailBounced`        | 330   | Email bounced (e.g., full mailbox)                                       |
| `EmailMarkedAsSpam`   | 340   | Email was sent but marked as spam                                        |
| `EmailRejected`       | 350   | Email was rejected by recipient server                                   |
| `MissingEmailAddress` | 400   | Email address was missing from invoice                                   |
| `NA`                  | 1000  | General configuration indicates nothing should be sent                   |
| `NotSent`             | 9999  | Invoice will not be sent                                                 |

## Implementation Examples

### JavaScript Example

```javascript
async function createInvoiceWithSend(invoiceData, sendConfig) {
  const invoiceWithSend = {
    ...invoiceData,
    Send: sendConfig
  };

  const response = await fetch('https://api.farpay.io/v2/invoices', {
    method: 'POST',
    headers: {
      'X-API-KEY': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(invoiceWithSend)
  });

  return await response.json();
}

// Create invoice with SMS delivery
const invoiceData = {
  CustomerNumber: "12345",
  InvoiceNumber: "INV-001",
  Amount: 125.50,
  Currency: "DKK",
  DueDate: "2023-02-15",
  Description: "Monthly subscription"
};

const smsSendConfig = {
  Channel: "SMS",
  Status: "Queue",
  ToAddress: "+4533445566",
  ScheduleSendDate: "2024-05-31 15:55",
  Note: "Your invoice is ready for payment"
};

createInvoiceWithSend(invoiceData, smsSendConfig)
  .then(result => {
    console.log('Invoice created with SMS delivery:', result);
  })
  .catch(error => {
    console.error('Failed to create invoice:', error);
  });
```

### Python Example

```python
import requests
from datetime import datetime, timedelta

def create_invoice_with_send(invoice_data, send_config, api_key):
    invoice_with_send = {
        **invoice_data,
        "Send": send_config
    }
    
    response = requests.post(
        'https://api.farpay.io/v2/invoices',
        headers={
            'X-API-KEY': api_key,
            'Content-Type': 'application/json'
        },
        json=invoice_with_send
    )
    
    return response.json()

# Create invoice with email delivery
invoice_data = {
    "CustomerNumber": "12345",
    "InvoiceNumber": "INV-001",
    "Amount": 125.50,
    "Currency": "DKK",
    "DueDate": "2023-02-15",
    "Description": "Monthly subscription"
}

# Schedule for tomorrow at 10:00 AM
tomorrow = datetime.now() + timedelta(days=1)
schedule_time = tomorrow.strftime("%Y-%m-%d 10:00")

email_send_config = {
    "Channel": "Email",
    "Status": "Queue",
    "ToAddress": "customer@example.com",
    "ScheduleSendDate": schedule_time,
    "Note": "Please find your invoice attached. Thank you for your business!"
}

result = create_invoice_with_send(invoice_data, email_send_config, 'your-api-key')
print('Invoice created with email delivery:', result)
```

## Scheduling Considerations

### Schedule Send Date

* **Format**: `YYYY-MM-DD HH:MM`
* **Approximate timing**: Send schedules run on minute intervals
* **Peak handling**: High volume may cause slight delays
* **Timezone**: Uses system timezone

### Best Practices for Scheduling

1. **Avoid peak hours** - Schedule during off-peak times for better reliability
2. **Consider timezone** - Account for customer timezone when scheduling
3. **Test scheduling** - Verify scheduling works in your environment
4. **Monitor status** - Check send status after scheduled time

## Channel-Specific Considerations

### SMS Channel

* **Character limits** - Long messages may result in higher charges
* **International numbers** - Use proper country code format
* **Delivery confirmation** - SMS delivery is generally reliable

### Email Channel

* **Attachment size** - Large attachments may affect delivery
* **Spam filters** - Ensure proper email configuration
* **Bounce handling** - Monitor for bounced emails

### XML Channel (E-boks)

* **GLN validation** - Ensure GLN number is valid
* **Format compliance** - XML must comply with E-boks standards
* **Delivery tracking** - E-boks provides delivery confirmation

### Print Channel

* **No address required** - Uses default print configuration
* **Queue management** - Prints are queued for batch processing
* **Physical delivery** - Requires manual handling

## Error Handling

### Common Send Errors

| Error Status        | Description            | Solution                               |
| ------------------- | ---------------------- | -------------------------------------- |
| `ErrorSendingEmail` | SMTP connection issues | Check email server configuration       |
| `WrongEmailAddress` | Invalid email address  | Validate email format                  |
| `EmailBounced`      | Recipient mailbox full | Contact customer for alternative email |
| `EmailMarkedAsSpam` | Spam filter blocked    | Improve email reputation               |
| `EmailRejected`     | Server rejected email  | Check recipient server settings        |

### Error Recovery

```javascript
async function handleSendError(invoiceId, errorStatus) {
  switch (errorStatus) {
    case 310: // ErrorSendingEmail
      console.log('Technical email issue - retry later');
      break;
    case 320: // WrongEmailAddress
      console.log('Invalid email - update customer record');
      break;
    case 330: // EmailBounced
      console.log('Mailbox full - contact customer');
      break;
    case 340: // EmailMarkedAsSpam
      console.log('Spam filter issue - review email content');
      break;
    case 350: // EmailRejected
      console.log('Server rejection - check recipient settings');
      break;
    default:
      console.log('Unknown send error:', errorStatus);
  }
}
```

## Monitoring Send Status

### Check Send Status

```javascript
async function checkSendStatus(invoiceId) {
  const response = await fetch(`https://api.farpay.io/v2/invoices/${invoiceId}`, {
    headers: {
      'X-API-KEY': 'your-api-key',
      'Accept': 'application/json'
    }
  });
  
  const invoice = await response.json();
  return invoice.SendStatus; // Returns numeric status value
}

// Monitor send status
const status = await checkSendStatus(12345);
console.log('Send status:', status);

if (status === 200) {
  console.log('Invoice sent successfully');
} else if (status >= 300) {
  console.log('Send error occurred');
}
```

## Best Practices

### Send Configuration

1. **Validate addresses** - Ensure correct format for each channel
2. **Test channels** - Verify each channel works in your environment
3. **Monitor status** - Regularly check send status for errors
4. **Handle errors** - Implement proper error handling for failed sends

### Scheduling

1. **Avoid conflicts** - Don't schedule multiple sends to same customer
2. **Consider timezone** - Account for customer timezone
3. **Plan for delays** - Allow time for processing and delivery
4. **Monitor queues** - Check for queued sends regularly

### Content

1. **Keep SMS short** - Avoid long messages that increase costs
2. **Professional emails** - Use proper email formatting and content
3. **Clear messaging** - Ensure send notes are clear and professional
4. **Brand consistency** - Maintain consistent messaging across channels

## Related Endpoints

* [Invoices](invoices#) - Invoice creation and management
* [Customers](customers#) - Customer information and preferences
* [Deliveries](deliveries#) - Batch file processing

<br />