# Email testing for Selenium
Learn how to integrate Mailosaur email testing into Selenium.
## What you'll find in this guide
- How to test various aspects of emails
- Testing links and codes
- Managing email tests
## What you'll need
- An understanding of Selenium and how it works.
- A Mailosaur account. You can [start a free trial](/app/signup) if you don't have one.
- A Selenium project with Mailosaur's API client configured. [See our short guide](/docs/automation/selenium/quickstart) on this.
## Basic usage
To perform email testing with Selenium, all you need to do is:
1. Send an email message to your Mailosaur inbox (e.g. by requesting a password reset)
2. Connect to the Mailosaur API with the official client library.
3. Search for the email you sent in step 1.
4. Perform assertions in the same way you would for any other test.
To learn about Server IDs, and what to replace SERVER_ID with, [see sending test emails to Mailosaur](/docs/email-testing/sending-to-mailosaur).
```java
// Setup the API client
MailosaurClient mailosaur = new MailosaurClient("API_KEY");
MessageSearchParams params = new MessageSearchParams();
params.withServer("SERVER_ID");
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.withSentTo("my-test@SERVER_ID.mailosaur.net");
// Search for the message
Message message = mailosaur.messages().get(params, searchCriteria);
// Perform test assertions
assertEquals("Support", message.from().get(0).name());
assertEquals("noreply@acme.com", message.from().get(0).email());
```
```py
# Setup the API client
mailosaur = MailosaurClient("API_KEY")
criteria = SearchCriteria()
criteria.sent_to = "my-test@SERVER_ID.mailosaur.net"
# Search for the message
message = mailosaur.messages.get("SERVER_ID", criteria)
# Perform test assertions
self.assertEqual("Support", message.sender[0].name)
self.assertEqual("noreply@acme.com", message.sender[0].email)
```
```csharp
// Setup the API client
var mailosaur = new MailosaurClient("API_KEY");
var criteria = new SearchCriteria() {
SentTo = "my-test@SERVER_ID.mailosaur.net"
};
// Search for the message
var message = mailosaur.Messages.Get("SERVER_ID", criteria);
// Perform test assertions
Assert.Equal("Support", message.From[0].Name);
Assert.Equal("noreply@acme.com", message.From[0].Email);
```
```ruby
# Setup the API client
mailosaur = Mailosaur::MailosaurClient.new("API_KEY")
criteria = Mailosaur::Models::SearchCriteria.new()
criteria.sent_to = "my-test@SERVER_ID.mailosaur.net"
# Search for the message
message = mailosaur.messages.get("SERVER_ID", criteria)
# Perform test assertions
assert_equal("Support", message.from[0].name)
assert_equal("noreply@acme.com", message.from[0].email)
```
```js
// Setup the API client
const MailosaurClient = require("mailosaur");
const mailosaur = new MailosaurClient("API_KEY");
// Search for the message
const message = await mailosaur.messages.get("SERVER_ID", {
sentTo: "my-test@SERVER_ID.mailosaur.net",
});
// Perform test assertions
expect(message.from[0].name).toBe("Support");
expect(message.from[0].email).toBe("noreply@acme.com");
```
This example will search for the email address that a message was sent to, but you can also search using any of the below criteria:
| **Parameter** | **Description** |
| ------------- | ------------------------------------------------------------- |
| sentTo | The full email address to which the target message was sent |
| sentFrom | The full email address from which the target message was sent |
| subject | Finds messages where the subject line contains this text |
| body | Finds messages where the message body contains this text |
### Test email addresses
Each inbox in your account (also known as a server) has a unique identifier, referred to as a **Server ID**. This ID is used to give your inbox a domain name like this: `SERVER_ID.mailosaur.net`.
This domain supports a wildcard email pattern, meaning any email address ending `@SERVER_ID.mailosaur.net` works out of the box.
**You don't need to create email addresses** before using them, they just work! However, if you need help thinking of a unique email address, you can use this helper method:
```java
String emailAddress = mailosaur.servers().generateEmailAddress("SERVER_ID");
System.out.println(emailAddress); // "bgwqj@SERVER_ID.mailosaur.net"
```
```py
email_address = mailosaur.servers.generate_email_address("SERVER_ID")
print(email_address) # "bgwqj@SERVER_ID.mailosaur.net"
```
```csharp
var emailAddress = mailosaur.Servers.GenerateEmailAddress("SERVER_ID");
Console.WriteLine(emailAddress); // "bgwqj@SERVER_ID.mailosaur.net"
```
```ruby
email_address = mailosaur.servers.generate_email_address("SERVER_ID")
puts(email_address) # "bgwqj@SERVER_ID.mailosaur.net"
```
```js
const emailAddress = mailosaur.servers.generateEmailAddress("SERVER_ID");
console.log(emailAddress); // "bgwqj@SERVER_ID.mailosaur.net"
```
## Find an email
Search for a specific message within your inbox. It's always better to use `messages.get()`, as it will automatically wait for messages to arrive, and will return the full message result.
```java
MessageSearchParams params = new MessageSearchParams();
params.withServer("SERVER_ID");
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.withSentTo("test123@SERVER_ID.mailosaur.net");
Message message = mailosaur.messages().get(params, searchCriteria);
System.out.println(message.html().body());
```
```py
criteria = SearchCriteria()
criteria.sent_to = "test123@SERVER_ID.mailosaur.net"
message = mailosaur.messages.get("SERVER_ID", criteria)
print(message.html.body)
```
```csharp
var criteria = new SearchCriteria() {
SentTo = "test123@SERVER_ID.mailosaur.net"
};
var message = mailosaur.Messages.Get("SERVER_ID", criteria);
Console.WriteLine(message.Html.Body);
```
```ruby
criteria = Mailosaur::Models::SearchCriteria.new()
criteria.sent_to = "test123@SERVER_ID.mailosaur.net"
message = mailosaur.messages.get("SERVER_ID", criteria)
puts(message.html.body)
```
```js
// Search for the message
const message = await mailosaur.messages.get("SERVER_ID", {
sentTo: "my-test@SERVER_ID.mailosaur.net",
});
console.log(message.html.body);
```
### Time range for searching
By default searches only look for messages received in the last hour. If you want to look further back than this, just set the 'received after' parameter.
```java
// Calculate a timestamp for yesterday
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, -1);
long yesterday = calendar.getTimeInMillis();
// Use this timestamp in the search
MessageSearchParams params = new MessageSearchParams();
params.withServer("SERVER_ID");
params.withReceivedAfter(yesterday);
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.withSentTo("test123@SERVER_ID.mailosaur.net");
Message message = mailosaur.messages().get(params, searchCriteria);
```
```python
# Calculate a datetime for yesterday
yesterday = datetime.today() - timedelta(days=1)
criteria = SearchCriteria()
criteria.sent_to = "test123@SERVER_ID.mailosaur.net"
# Use this timestamp in the search
message = mailosaur.messages.get("SERVER_ID", criteria, received_after=yesterday)
```
```csharp
// Calculate a datetime for yesterday
var yesterday = DateTime.Today.AddDays(-1);
var criteria = new SearchCriteria() {
SentTo = "test123@SERVER_ID.mailosaur.net"
};
// Use this timestamp in the search
var message = mailosaur.Messages.Get("SERVER_ID", criteria, receivedAfter: yesterday);
```
```ruby
# Calculate a datetime for yesterday
yesterday = Date.today - 1
criteria = Mailosaur::Models::SearchCriteria.new()
criteria.sent_to = "test123@SERVER_ID.mailosaur.net"
# Use this timestamp in the search
message = mailosaur.messages.get("SERVER_ID", criteria)
```
```js
// Calculate a datetime for yesterday
const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);
// Use this timestamp in the search
const message = await mailosaur.messages.get("SERVER_ID", {
sentTo: "my-test@SERVER_ID.mailosaur.net",
}, {
receivedAfter: yesterday
});
```
### "No matching messages" troubleshooting
If you see the error "No matching messages found in time" when searching for messages:
- Ensure that the target email or SMS message is visible in the Mailosaur Dashboard, as it may not have arrived at all.
- Check when the message arrived. By default, searches only include messages received within the last hour. See "time range for searching" above on how to override this.
- Check you have correctly set the **sent to** parameter in your search criteria.
## Other ways to fetch emails
> [!WARNING]
>
> #### It is usually better to use `messages.get()`
>
> The `list` and `search` methods will only return basic summaries, meaning several properties (including the message body) are not included. To get this data, you need to use [`.getById()`](#6-messagesgetbyidid). Instead, we recommend using the [`messages.get()`](#2-messagesgetserver-criteria-options) as this automatically waits for a matching result and returns the message in the result.
### List current inbox contents
See a full list of everything currently in your inbox.
```java
// List the most recent messages
MessageListParams params = new MessageListParams();
params.withServer("SERVER_ID");
MessageListResult result = mailosaur.messages().list(params);
// Get the most recent message (the first one in the list)
MessageSummary latestMessage = result.items().get(0);
// Get the full message object
Message message = mailosaur.messages().getById(latestMessage.id());
System.out.println(message.html().body());
```
```py
# List the most recent messages
result = mailosaur.messages.list("SERVER_ID")
# Get the most recent message (the first one in the list)
latest_message = result.items[0]
# Get the full message object
message = mailosaur.messages.get_by_id(latest_message.id)
print(message.html.body)
```
```csharp
// List the most recent messages
var result = mailosaur.Messages.List("SERVER_ID");
// Get the most recent message (the first one in the list)
var latestMessage = result.Items[0];
// Get the full message object
var message = mailosaur.Messages.GetById(latestMessage.Id);
Console.WriteLine(message.Html.Body);
```
```ruby
# List the most recent messages
result = mailosaur.messages.list("SERVER_ID")
# Get the most recent message (the first one in the list)
latest_message = result.items[0]
# Get the full message object
message = mailosaur.messages.get_by_id(latest_message.id)
puts(message.html.body)
```
```js
// List the most recent messages
const result = await mailosaur.messages.list("SERVER_ID");
// Get the most recent message (the first one in the list)
const latestMessage = result.items[0];
// Get the full message object
const message = await mailosaur.messages.getById(latestMessage.id);
console.log(message.html.body);
```
### Searching for multiple messages
Identify if multiple messages meet the same criteria.
```java
// Search for all messages sent to someone@SERVER_ID.mailosaur.net.
SearchCriteria criteria = new SearchCriteria();
criteria.withSentTo("someone@SERVER_ID.mailosaur.net");
// Limit results to the first 10 matches only.
MessageSearchParams params = new MessageSearchParams();
params.withServer("SERVER_ID")
.withPage(0)
.withItemsPerPage(10);
MessageListResult result = mailosaur.messages().search(params, criteria);
// Get the most recent message (the first one in the list)
MessageSummary latestMessage = result.items().get(0);
// Get the full message object
Message message = mailosaur.messages().getById(latestMessage.id());
System.out.println(message.html().body());
```
```py
# Search for all messages sent to someone@SERVER_ID.mailosaur.net.
criteria = SearchCriteria()
criteria.sent_to = "someone@SERVER_ID.mailosaur.net"
# Limit results to the first 10 matches only.
result = mailosaur.messages.search("SERVER_ID", criteria, page=0, items_per_page=10)
# Get the most recent message (the first one in the list)
latest_message = result.items[0]
# Get the full message object
message = mailosaur.messages.get_by_id(latest_message.id)
print(message.html.body)
```
```csharp
// Search for all messages sent to someone@SERVER_ID.mailosaur.net.
var criteria = new SearchCriteria() {
SentTo = "someone@SERVER_ID.mailosaur.net"
};
// Limit results to the first 10 matches only.
var result = mailosaur.Messages.Search("SERVER_ID", criteria, page: 0, itemsPerPage: 10);
// Get the most recent message (the first one in the list)
var latestMessage = result.Items[0];
// Get the full message object
var message = mailosaur.Messages.GetById(latestMessage.Id);
Console.WriteLine(message.Html.Body);
```
```ruby
# Search for all messages sent to someone@SERVER_ID.mailosaur.net.
criteria = Mailosaur::Models::SearchCriteria.new()
criteria.sent_to = "someone@SERVER_ID.mailosaur.net"
# Limit results to the first 10 matches only.
result = mailosaur.messages.search("SERVER_ID", criteria, page: 0, items_per_page: 10)
# Get the most recent message (the first one in the list)
latest_message = result.items[0]
# Get the full message object
message = mailosaur.messages.get_by_id(latest_message.id)
puts(message.html.body)
```
```js
// Search for all messages sent to someone@SERVER_ID.mailosaur.net.
// Limit results to the first 10 matches only.
const result = await mailosaur.messages.search(
"SERVER_ID",
{
sentTo: "someone@SERVER_ID.mailosaur.net",
},
{
page: 0,
itemsPerPage: 10,
}
);
// Get the most recent message (the first one in the list)
const latestMessage = result.items[0];
// Get the full message object
const message = await mailosaur.messages.getById(latestMessage.id);
console.log(message.html.body);
```
## Common test scenarios
### Testing basic properties
Once you have fetched an email (e.g. using `messages.get`), you can easily test the properties of that email:
```java
// Test the email subject line
assertEquals("Password reset", message.subject());
// Test sender information
assertEquals("Support", message.from().get(0).name());
assertEquals("noreply@acme.com", message.from().get(0).email());
// Test recipient information
assertEquals("John Smith", message.to().get(0).name());
assertEquals("john@SERVER.mailosaur.net", message.to().get(0).email());
```
```py
# Test the email subject line
self.assertEqual("Password reset", message.subject)
# Test sender information
self.assertEqual("Support", message.sender[0].name)
self.assertEqual("noreply@acme.com", message.sender[0].email)
# Test recipient information
self.assertEqual("John Smith", message.to[0].name)
self.assertEqual("john@SERVER.mailosaur.net", message.to[0].email)
```
```csharp
// Test the email subject line
Assert.Equal("Password reset", message.Subject);
// Test sender information
Assert.Equal("Support", message.From[0].Name);
Assert.Equal("noreply@acme.com", message.From[0].Email);
// Test recipient information
Assert.Equal("John Smith", message.To[0].Name);
Assert.Equal("john@SERVER.mailosaur.net", message.To[0].Email);
```
```ruby
# Test the email subject line
assert_equal("Password reset", message.subject)
# Test sender information
assert_equal("Support", message.from[0].name)
assert_equal("noreply@acme.com", message.from[0].email)
# Test recipient information
assert_equal("John Smith", message.to[0].name)
assert_equal("john@SERVER.mailosaur.net", message.to[0].email)
```
```js
// Test the email subject line
expect(message.subject).toBe("Password reset");
// Test sender information
expect(message.from[0].name).toBe("Support");
expect(message.from[0].email).toBe("noreply@acme.com");
// Test recipient information
expect(message.from[0].name).toBe("John Smith");
expect(message.from[0].email).toBe("john@SERVER.mailosaur.net");
```
#### Testing carbon-copy recipients
```java
// Carbon copy (CC) recipients
assertEquals("Jane Smith", message.cc().get(0).name());
assertEquals("jane@SERVER.mailosaur.net", message.cc().get(0).email());
// Blind carbon copy (BCC) recipients
assertEquals("Jill Smith", message.bcc().get(0).name());
assertEquals("jill@SERVER.mailosaur.net", message.bcc().get(0).email());
```
```py
# Carbon copy (CC) recipients
self.assertEqual("Jane Smith", message.cc[0].name)
self.assertEqual("jane@SERVER.mailosaur.net", message.cc[0].email)
# Blind carbon copy (BCC) recipients
self.assertEqual("Jill Smith", message.bcc[0].name)
self.assertEqual("jill@SERVER.mailosaur.net", message.bcc[0].email)
```
```csharp
// Carbon copy (CC) recipients
Assert.Equal("Jane Smith", message.Cc[0].Name);
Assert.Equal("jane@SERVER.mailosaur.net", message.Cc[0].Email);
// Blind carbon copy (BCC) recipients
Assert.Equal("Jill Smith", message.Bcc[0].Name);
Assert.Equal("jill@SERVER.mailosaur.net", message.Bcc[0].Email);
```
```ruby
# Carbon copy (CC) recipients
assert_equal("Jane Smith", message.cc[0].name)
assert_equal("jane@SERVER.mailosaur.net", message.cc[0].email)
# Blind carbon copy (BCC) recipients
assert_equal("Jill Smith", message.bcc[0].name)
assert_equal("jill@SERVER.mailosaur.net", message.bcc[0].email)
```
```js
// Carbon copy (CC) recipients
expect(message.cc[0].name).toBe("Jane Smith");
expect(message.cc[0].email).toBe("jane@SERVER.mailosaur.net");
// Blind carbon copy (BCC) recipients
expect(message.bcc[0].name).toBe("Jill Smith");
expect(message.bcc[0].email).toBe("jill@SERVER.mailosaur.net");
```
### Testing email contents
Most emails will contain separate HTML and plain text content. You can see below how to test either content type:
#### Plain text content
```java
// Check that the email contains some text
System.out.println(message.text().body()); // "Hi Jason, ..."
```
```py
# Check that the email contains some text
print(message.text.body) # "Hi Jason, ..."
```
```csharp
// Check that the email contains some text
Console.WriteLine(message.Text.Body); // "Hi Jason, ..."
```
```ruby
# Check that the email contains some text
puts(message.text.body) # "Hi Jason, ..."
```
```js
// Check that the email contains some text
console.log(message.text.body); // "Hi Jason, ..."
```
#### HTML content
When testing HTML content, you can perform basic contains or equals assertions in the same way as with plain text content:
```java
// Check that raw HTML contains some expected content
System.out.println(message.html().body()); // "Hello world"
```
```py
# Check that raw HTML contains some expected content
print(message.html.body) # "Hello world"
```
```csharp
// Check that raw HTML contains some expected content
Console.WriteLine(message.Html.Body); // "Hello world"
```
```ruby
# Check that raw HTML contains some expected content
puts(message.html.body) # "Hello world"
```
```js
// Check that raw HTML contains some expected content
console.log(message.html.body); // "Hello world"
```
### Testing links
Any links that are found in the content of your email are instantly available via the `html.links` or `text.links` arrays, depending on which content the link was found in:
```java
// Working with links in HTML content
Link linkInHtml = message.html().links().get(0);
assertEquals("Google Search", linkInHtml.text());
assertEquals("https://www.google.com/", linkInHtml.href());
// Working with links in plain text content
Link linkInPlainText = message.text().links().get(0);
assertEquals("https://www.google.com/", linkInPlainText.href());
```
```py
# Working with links in HTML content
link_in_html = message.html.links[0]
self.assertEqual("Google Search", link_in_html.text)
self.assertEqual("https://www.google.com/", link_in_html.href)
# Working with links in plain text content
link_in_plain_text = message.text.links[0]
self.assertEqual("https://www.google.com/", link_in_plain_text.href)
```
```csharp
// Working with links in HTML content
var linkInHtml = message.Html.Links[0];
Assert.Equal("Google Search", linkInHtml.Text);
Assert.Equal("https://www.google.com/", linkInHtml.Href);
// Working with links in plain text content
var linkInPlainText = message.Text.Links[0];
Assert.Equal("https://www.google.com/", linkInPlainText.Href);
```
```ruby
# Working with links in HTML content
link_in_html = message.html.links[0]
assert_equal("Google Search", link_in_html.text)
assert_equal("https://www.google.com/", link_in_html.href)
# Working with links in plain text content
link_in_plain_text = message.text.links[0]
assert_equal("https://www.google.com/", link_in_plain_text.href)
```
```js
// Working with links in HTML content
const linkInHtml = message.html.links[0];
expect(linkInHtml.text).toBe("Google Search");
expect(linkInHtml.href).toBe("https://www.google.com/");
// Working with links in plain text content
const linkInPlainText = message.text.links[0];
expect(linkInPlainText.href).toBe("https://www.google.com/");
```
#### Clicking a link
If you just need to simulate a link being clicked and do not need to do anything on the target page, you can do this with `HttpClient`:
```java
String href = message.html().links().get(0).href();
// Make an HTTP call to simulate someone clicking a link
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create(href)).build();
var response = client.send(request, null);
System.out.println(response.statusCode()); // 200
```
```py
import requests
# ...
href = message.html.links[0].href
# Make an HTTP call to simulate someone clicking a link
response = requests.get(href)
print(response.status_code) # 200
```
```csharp
var href = message.Html.Links[0].Href;
// Make an HTTP call to simulate someone clicking a link
using (var client = new HttpClient()) {
var result = await client.GetAsync(href);
Console.WriteLine(result.StatusCode); // 200
}
```
```ruby
href = message.html.links[0].href
# Make an HTTP call to simulate someone clicking a link
uri = URI(href)
Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https') do |http|
request = Net::HTTP::Get.new uri
response = http.request request # Net::HTTPResponse object
puts(response.code) # 200
end
```
```js
const https = require("https");
// ...
const href = message.html.links[0].href;
// Make an HTTP call to trigger the web beacon
https.get(href, (r) => console.log(r.statusCode)); // 200
```
### Testing verification codes
Codes are automatically extracted from the content of your message. They are then made available via the `html.codes` or `text.codes` arrays:
```java
// Working with codes in HTML content
Link codeInHtml = message.html().codes().get(0);
assertEquals("456812", codeInHtml.value());
// Working with codes in plain text content
Link codeInText = message.text().codes().get(0);
assertEquals("456812", codeInText.value());
```
```py
# Working with codes in HTML content
code_in_html = message.html.codes[0]
self.assertEqual("456812", code_in_html.value)
# Working with codes in plain text content
code_in_text = message.text.codes[0]
self.assertEqual("456812", code_in_text.value)
```
```csharp
// Working with codes in HTML content
var codeInHtml = message.Html.Codes[0];
Assert.Equal("456812", codeInHtml.Value);
// Working with codes in plain text content
var codeInText = message.Text.Codes[0];
Assert.Equal("456812", codeInText.Value);
```
```ruby
# Working with codes in HTML content
code_in_html = message.html.codes[0]
assert_equal("456812", code_in_html.value)
# Working with codes in plain text content
code_in_text = message.text.codes[0]
assert_equal("456812", code_in_text.value)
```
```js
// Working with codes in HTML content
const codeInHtml = message.html.codes[0];
expect(codeInHtml.value).toBe("456812");
// Working with codes in plain text content
const codeInText = message.text.codes[0];
expect(codeInText.value).toBe("456812");
```
### Testing attachments
Any email attachments are made available via the attachments array:
```java
// Number of attachments found
System.out.println(message.attachments().size()); // 2
// Get the first attachment
Attachment attachment = message.attachments().get(0);
// Check attachment attributes
assertEquals("example.pdf", attachment.fileName());
assertEquals("application/pdf", attachment.contentType());
assertEquals(4028, attachment.length());
```
```py
# Number of attachments found
print(len(message.attachments)) # 2
# Get the first attachment
attachment = message.attachments[0]
# Check attachment attributes
self.assertEqual("example.pdf", attachment.file_name)
self.assertEqual("application/pdf", attachment.content_type)
self.assertEqual(4028, attachment.length)
```
```csharp
// Number of attachments found
Console.WriteLine(message.Attachments.Count);
// Get the first attachment
var attachment = message.Attachments[0];
// Check attachment attributes
Assert.Equal("example.pdf", attachment.FileName);
Assert.Equal("application/pdf", attachment.ContentType);
Assert.Equal(4028, attachment.Length);
```
```ruby
# Number of attachments found
puts(message.attachments.length) # 2
# Get the first attachment
attachment = message.attachments[0]
# Check attachment attributes
assert_equal("example.pdf", attachment.file_name)
assert_equal("application/pdf", attachment.content_type)
assert_equal(4028, attachment.length)
```
```js
// Number of attachments found
console.log(message.attachments.length); // 2
// Get the first attachment
const attachment = message.attachments[0];
// Check attachment attributes
expect(attachment.fileName).toBe("example.pdf");
expect(attachment.contentType).toBe("application/pdf");
expect(attachment.length).toBe(4028);
```
#### Save an attachment to disk
You can download and save attachments using this sample code:
```java
Attachment firstAttachment = message.attachments().get(0);
byte[] file = mailosaur.files().getAttachment(firstAttachment.id());
Files.write(Paths.get(firstAttachment.fileName()), file);
```
```py
first_attachment = message.attachments[0]
file = mailosaur.files.get_attachment(first_attachment.id).content
f = open(first_attachment.file_name, 'wb')
f.write(file)
f.close()
```
```csharp
var firstAttachment = message.Attachments[0];
var file = mailosaur.Files.GetAttachment(firstAttachment.Id);
File.WriteAllBytes(firstAttachment.FileName, file);
```
```ruby
first_attachment = message.attachments[0]
file = mailosaur.files.get_attachment(first_attachment.id)
File.open(first_attachment.file_name, 'wb') { |fp| fp.write(file) }
```
```js
const firstAttachment = message.Attachments[0];
const file = await mailosaur.files.getAttachment(firstAttachment.id);
fs.writeFileSync(firstAttachment.fileName, file);
```
#### Encoding attachments
In some scenarios you may need a base64-encoded copy of an attachment. You can achieve this using this sample code:
```java
Attachment firstAttachment = message.attachments().get(0);
byte[] file = mailosaur.files().getAttachment(firstAttachment.id());
String base64 = new String(Base64.getEncoder().encode(file));
System.out.println(base64);
```
```py
first_attachment = message.attachments[0]
file = mailosaur.files.get_attachment(first_attachment.id).content
base64 = base64.b64encode(file)
print(base64)
```
```csharp
var firstAttachment = message.Attachments[0];
var file = mailosaur.Files.GetAttachment(firstAttachment.Id);
var base64 = Convert.ToBase64String(file);
Console.WriteLine(base64);
```
```ruby
first_attachment = message.attachments[0]
file = mailosaur.files.get_attachment(first_attachment.id)
base64 = Base64.encode64(file)
puts base64
```
```js
const firstAttachment = message.Attachments[0];
const file = await mailosaur.files.getAttachment(firstAttachment.id);
const base64 = file.toString("base64");
console.log(base64);
```
### Testing images and web beacons
Any images found within the HTML content of an email are made available via the `html.images` array:
```java
// Number of images found
System.out.println(message.html().images().size());
// Get the first image
var image = message.html().images().get(0);
// Check image attributes
assertEquals("https://example.com/balloon.png", image.src());
assertEquals("A hot air balloon", image.alt());
```
```py
# Number of images found
print(len(message.html.images))
# Get the first image
image = message.html.images[0]
# Check image attributes
self.assertEqual("https://example.com/balloon.png", image.src)
self.assertEqual("A hot air balloon", image.alt)
```
```csharp
// Number of images found
Console.WriteLine(message.Html.Images.Count);
// Get the first image
var image = message.Html.Images[0];
// Check image attributes
Assert.Equal("https://example.com/balloon.png", image.Src)
Assert.Equal("A hot air balloon", image.Alt)
```
```ruby
# Number of images found
puts(message.html.images.length)
# Get the first image
image = message.html.images[0]
# Check image attributes
assert_equal("https://example.com/balloon.png", image.src)
assert_equal("A hot air balloon", image.alt)
```
```js
// Number of images found
console.log(message.html.images.length);
// Get the first image
const image = message.html.images[0];
// Check image attributes
expect(image.src).toBe("https://example.com/balloon.png");
expect(image.alt).toBe("A hot air balloon");
```
To test whether an image is accessible online, or that a [web beacon](https://en.wikipedia.org/wiki/Web_beacon) is working as expected, you can simply perform an HTTP request:
```java
// Make an HTTP call to trigger the web beacon
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder(URI.create(image.src())).build();
var response = client.send(request, null);
System.out.println(response.statusCode()); // 200
```
```py
import requests
# ...
# Make an HTTP call to trigger the web beacon
response = requests.get(image.src)
print(response.status_code) # 200
```
```csharp
// Make an HTTP call to trigger the web beacon
using (var client = new HttpClient()) {
var result = await client.GetAsync(image.Src);
Console.WriteLine(result.StatusCode); // 200
}
```
```ruby
# Make an HTTP call to trigger the web beacon
uri = URI(image.src)
Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https') do |http|
request = Net::HTTP::Get.new uri
response = http.request request
puts(response.code) # 200
end
```
```js
const https = require("https");
// ...
// Make an HTTP call to trigger the web beacon
https.get(image.src, (r) => console.log(r.statusCode)); // 200
```
### Sending an email
If your product is capable of handling inbound emails, you can use Mailosaur’s sending feature to trigger this functionality in your product.
The `messages.create` command creates and sends an email to a verified external email address:
```java
CodeMessageCreateOptions options = new MessageCreateOptions();
options.withTo("verified-address@example.com")
.withSend(true)
.withSubject("Request")
.withText("Please can you give us a call back?");
mailosaur.messages().create("SERVER_ID", options);
```
```py
recipient = "verified-address@example.com"
subject = "Request"
text = "Please can you give us a call back?"
options = MessageCreateOptions(
recipient, True, subject, text=text)
mailosaur.messages.create("SERVER_ID", options)
```
```csharp
mailosaur.Messages.Create("SERVER_ID", new MessageCreateOptions()
{
To = "verified-address@example.com",
Subject = "Request",
Text = "Please can you give us a call back?",
Send = true
}
);
```
```ruby
options = Mailosaur::Models::MessageCreateOptions.new()
options.to = "verified-address@example.com"
options.subject = "Request"
options.text = "Please can you give us a call back?"
options.send = true
mailosaur.messages.create('SERVER_ID', options)
```
```js
await mailosaur.messages.create("SERVER_ID", {
to: "verified-address@example.com",
subject: "Request",
text: "Please can you give us a call back?",
send: true,
});
```
The options available to use with this method are:
| Parameter | Description |
| ----------- | ------------------------------------------------------------------------------------ |
| send | This must be set to true if you are sending an outbound email |
| to | The email address to which the email will be sent. Must be a verified email address. |
| subject | The email subject line |
| text | The plain text body of the email. |
| html | The HTML body of the email. |
| attachments | Optional attachments (see 'include attachments' below) |
#### Include attachments
You can include attachments in emails sent via the API, by including an array of base64-encoded attachment objects:
```java
Attachment attachment = new Attachment();
attachment.withFileName("cat.png");
attachment.withContent("{BASE64_ENCODED_FILE}");
attachment.withContentType("image/png");
CodeMessageCreateOptions options = new MessageCreateOptions();
options.withTo("verified-address@example.com")
.withSend(true)
.withSubject("Request")
.withText("Please can you give us a call back?")
.withAttachments(Arrays.asList(new Attachment[] { attachment }));
mailosaur.messages().create("SERVER_ID", options);
```
```py
attachment = Attachment()
attachment.file_name = "cat.png"
attachment.content = "{BASE64_ENCODED_FILE}"
attachment.content_type = "image/png"
attachments = [attachment]
recipient = "verified-address@example.com"
subject = "Request"
text = "Please can you give us a call back?"
options = MessageCreateOptions(
recipient, True, subject, text=text, attachments=attachments)
mailosaur.messages.create("SERVER_ID", options)
```
```csharp
var attachment = new Attachment()
{
FileName = "cat.png",
Content = "{BASE64_ENCODED_FILE}",
ContentType = "image/png"
};
mailosaur.Messages.Create("SERVER_ID", new MessageCreateOptions()
{
To = "verified-address@example.com",
Subject = "Request",
Text = "Please can you give us a call back?",
Attachments = new List() { attachment },
Send = true
}
);
```
```ruby
attachment = Mailosaur::Models::Attachment.new()
attachment.file_name = "cat.png"
attachment.content = "{BASE64_ENCODED_FILE}"
attachment.content_type = "image/png"
options = Mailosaur::Models::MessageCreateOptions.new()
options.to = "verified-address@example.com"
options.subject = "Request"
options.text = "Please can you give us a call back?"
options.attachments = [attachment]
options.send = true
mailosaur.messages.create('SERVER_ID', options)
```
```js
const attachment = {
fileName: "cat.png",
content: "{BASE64_ENCODED_FILE}",
contentType: "image/png",
};
await mailosaur.messages.create("SERVER_ID", {
to: "verified-address@example.com",
subject: "Request",
text: "Please can you give us a call back?",
attachments: [attachment],
send: true,
});
```
### Replying to an email
If your product handles email replies, the Mailosaur reply feature simulates this. When you reply, the message is sent back to the original account:
```java
MessageReplyOptions options = new MessageReplyOptions();
options.withText("FYI");
mailosaur.messages().reply("MESSAGE_ID", options);
```
```py
options = MessageReplyOptions(text="FYI")
mailosaur.messages.reply("MESSAGE_ID", options)
```
```csharp
mailosaur.Messages.Reply("MESSAGE_ID", new MessageReplyOptions()
{
Text = "FYI"
}
);
```
```ruby
options = Mailosaur::Models::MessageReplyOptions.new()
options.text = "FYI"
mailosaur.messages.reply("MESSAGE_ID", options)
```
```js
await mailosaur.messages.reply("MESSAGE_ID", {
text: "FYI",
});
```
| Parameter | Description |
| ----------- | ------------------------------------------------------ |
| text | Any additional text content to include in the reply |
| html | Any additional HTML content to include in the reply |
| subject | Optionally override the default subject line |
| attachments | Optional attachments (see 'include attachments' above) |
### Forwarding a message to email
You can forward messages from your Mailosaur account to external email addresses either one-by-one, or via the creation of automated forwarding rules. Before you can forward messages, **you must set up a [verified external email address](/docs/managing-your-account/external-email-addresses)**, so you can send email to it:
```java
MessageForwardOptions options = new MessageForwardOptions();
options.withTo("verified-address@example.com")
.withText("FYI");
mailosaur.messages().forward("MESSAGE_ID", options);
```
```py
recipient = "verified-address@example.com"
options = MessageForwardOptions(recipient, text="FYI")
mailosaur.messages.forward("MESSAGE_ID", options)
```
```csharp
mailosaur.Messages.Forward("MESSAGE_ID", new MessageForwardOptions()
{
To = "verified-address@example.com",
Text = "FYI"
}
);
```
```ruby
options = Mailosaur::Models::MessageForwardOptions.new()
options.to = 'verified-address@example.com'
options.text = 'FYI'
mailosaur.messages.forward('MESSAGE_ID', options)
```
```js
await mailosaur.messages.forward("MESSAGE_ID", {
to: "verified-address@example.com",
text: "FYI",
});
```
| Parameter | Description |
| --------- | ------------------------------------------------------------------------------------- |
| to | The email address to which the message will be sent. Must be a verified email address |
| text | Any additional text content to forward the message with |
| html | Any additional HTML content to forward the message with |
| subject | Optionally override the default subject line |
## Deleting messages
### Deleting an individual message
Permanently deletes a single message. Also deletes any attachments related to the message. This operation cannot be undone:
```java
mailosaur.messages().delete("MESSAGE_ID");
```
```py
mailosaur.messages.delete("MESSAGE_ID")
```
```csharp
mailosaur.Messages.Delete("MESSAGE_ID");
```
```ruby
mailosaur.messages.delete("MESSAGE_ID")
```
```js
await mailosaur.messages.del("MESSAGE_ID");
```
### Delete all messages
Permanently deletes all messages held in the specified inbox. Also deletes any attachments related to each message. This operation cannot be undone:
```java
mailosaur.messages().deleteAll("SERVER_ID");
```
```py
mailosaur.messages.delete_all("SERVER_ID")
```
```csharp
mailosaur.Messages.DeleteAll("SERVER_ID");
```
```ruby
mailosaur.messages.delete_all("SERVER_ID")
```
```js
await mailosaur.messages.deleteAll("SERVER_ID");
```
## See also
- [SMS testing guide](/docs/automation/selenium/sms-testing)
- [MFA/2FA guide](/docs/authenticator)