Random Email Address Code Examples
Test email addresses in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go
Each example below builds the same set of test addresses: a random alphanumeric username, a readable one such as [email protected], name-based patterns (john.doe, jdoe), a timestamped address and a batch of unique ones, plus a basic format check. The guide covers which domains are safe to put after the @, how unique the usernames really are and where validation stops; each language section then shows the code and what is specific to that language.
Prefer no code? The interactive Email address generator does the same in the browser.
Pick a domain that can never reach a stranger
The domain matters more than the random part. RFC 2606 reserves example.com, example.net and example.org for documentation, and the top-level names .test, .example, .invalid and .localhost, so nobody can ever register them and receive your test mail. Plausible-looking alternatives are not safe: test.org, company.com and mail.com are real registered domains, and a random name at gmail.com may be someone's inbox. .local is not a test name either; RFC 6762 gives it to multicast DNS on the local network.
Use .invalid when a test must prove that delivery fails. When a test must actually receive a message (a sign-up confirmation, a password reset link), send it to a local SMTP catcher such as Mailpit, or to a catch-all on a domain you control, never to a public address.
How unique the usernames are
A 12-character username from a-z0-9 has 3612 ≈ 4.7 × 1018 values (about 62 bits), and bin2hex(random_bytes(8)) gives 64 bits; duplicates in a test database are practically impossible. The readable pattern is a different story: 5 adjectives × 5 nouns × 900 numbers is only 22,500 addresses, and by the birthday bound a duplicate becomes more likely than not after about 177 of them. Grow the word lists, add digits, or check against a set before inserting into a column with a unique constraint.
Timestamp-based addresses are unique only within one process. time() has one-second resolution, so two runs in the same second produce identical lists, and parallel test workers can hit the same millisecond. Add a worker ID or a random suffix.
Secure or non-secure random?
For seed data and fixtures, predictability does no harm: the fast default generators are fine, and a fixed seed even helps, because the same test run creates the same users. A secure source (random_bytes(), crypto.getRandomValues(), secrets, SecureRandom, RandomNumberGenerator, crypto/rand) is needed only when the address itself grants something, for example a reply+<token>@ address that posts a comment, or a private alias that forwards to a real inbox. Treat that token like a password: at least 64 random bits.
Common mistakes
- Treating a regex as validation. The patterns in the examples only check the shape
[email protected]. RFC 5321 also limits the local part to 64 octets and the whole address to 254, and only a confirmation message proves a mailbox exists. - Rejecting valid addresses.
+tags, apostrophes (o'brien@) and subdomains are legal; a test set should contain them on purpose to see whether your form accepts them. - Accented names in name-based patterns.
josé.garcía@needs SMTPUTF8 (RFC 6531) support end to end. Transliterate names to ASCII before building the local part unless internationalized addresses are what you are testing. - Case handling. Lowercasing generated addresses is fine, but compare stored addresses case-insensitively; a unique index on a case-sensitive column lets
John@andjohn@coexist.
Common Use Cases
- Seeding user tables in development and staging databases (Django, Rails, Laravel, Spring, Entity Framework)
- Sign-up, login and password-reset flows in end-to-end tests (Cypress, Playwright, Selenium, Capybara)
- Unique fixtures for unit tests on tables with a unique email constraint
- Exercising email validation, normalization and deduplication code
- Load testing registration endpoints with many distinct accounts
Random Email Address Code Examples in PHP
Generate random email addresses in PHP for testing, QA, and development environments with customizable usernames and domains.
<?php
// Generate Random Email with Random Username
function randomEmail($domain = 'example.com') {
$username = bin2hex(random_bytes(8));
return $username . '@' . $domain;
}
echo "Random Email: " . randomEmail() . "\n";
echo "Custom Domain: " . randomEmail('example.org') . "\n";
// Generate Email with Readable Username
function readableEmail($domain = 'example.com') {
$adjectives = ['happy', 'sunny', 'clever', 'bright', 'quick'];
$nouns = ['panda', 'tiger', 'eagle', 'dolphin', 'falcon'];
$username = $adjectives[array_rand($adjectives)] .
$nouns[array_rand($nouns)] .
rand(100, 999);
return $username . '@' . $domain;
}
echo "Readable Email: " . readableEmail() . "\n";
// Generate Email from Name Pattern
function emailFromName($firstName, $lastName, $domain = 'example.net') {
$patterns = [
strtolower($firstName . '.' . $lastName),
strtolower($firstName[0] . $lastName),
strtolower($firstName . $lastName[0]),
strtolower($firstName . '_' . $lastName),
];
$username = $patterns[array_rand($patterns)];
return $username . '@' . $domain;
}
echo "Name-based: " . emailFromName('John', 'Doe') . "\n";
// Generate Test Email with Timestamp
function testEmail($domain = 'example.test') {
$username = 'test_' . time() . '_' . rand(1000, 9999);
return $username . '@' . $domain;
}
echo "Test Email: " . testEmail() . "\n";
// Generate Multiple Unique Emails
function generateEmails($count, $domain = 'example.com') {
$emails = [];
for ($i = 0; $i < $count; $i++) {
$emails[] = 'user' . uniqid() . '@' . $domain;
}
return $emails;
}
print_r(generateEmails(3));
// Validate Email Format
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
$email = randomEmail();
echo "Valid: " . (isValidEmail($email) ? 'Yes' : 'No');
How it works in PHP
PHP generates random emails by combining random usernames with domain names. Use bin2hex(random_bytes()) for completely random usernames, or combine word arrays for readable emails. uniqid() generates unique identifiers based on current time. For name-based emails, convert names to lowercase and use common patterns (firstname.lastname, firstinitiallastname). Always use the reserved domains from RFC 2606 (example.com, example.org, example.net, or any name under .test) so no message can reach a real mailbox. filter_var() with FILTER_VALIDATE_EMAIL validates email format according to RFC 5322.
Sample output
Random Email: [email protected] Custom Domain: [email protected] Readable Email: [email protected] Name-based: [email protected] Test Email: [email protected] Array ( [0] => [email protected] [1] => [email protected] [2] => [email protected] ) Valid: Yes
PHP notes
random_bytes()(PHP 7+) is cryptographically secure;rand()andarray_rand()are not, which is fine for the readable usernames.uniqid()is the current time in hex, not random: calls in the same microsecond collide;uniqid('', true)adds extra entropy.FILTER_VALIDATE_EMAILrejects non-ASCII addresses unless you addFILTER_FLAG_EMAIL_UNICODE(PHP 7.1+).- With fakerphp/faker,
safeEmail()only uses example.com, example.net and example.org.
Random Email Address Code Examples in JavaScript
Generate random email addresses in JavaScript/Node.js for testing, QA, and mock data with customizable patterns and domains.
// Generate Random Email with Random Username
function randomEmail(domain = 'example.com') {
const username = Math.random().toString(36).substring(2, 15);
return `${username}@${domain}`;
}
console.log('Random Email:', randomEmail());
console.log('Custom Domain:', randomEmail('example.org'));
// Generate Email with Readable Username
function readableEmail(domain = 'example.com') {
const adjectives = ['happy', 'sunny', 'clever', 'bright', 'quick'];
const nouns = ['panda', 'tiger', 'eagle', 'dolphin', 'falcon'];
const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
const noun = nouns[Math.floor(Math.random() * nouns.length)];
const num = Math.floor(Math.random() * 900) + 100;
return `${adj}${noun}${num}@${domain}`;
}
console.log('Readable Email:', readableEmail());
// Generate Email from Name Pattern
function emailFromName(firstName, lastName, domain = 'example.net') {
const patterns = [
`${firstName.toLowerCase()}.${lastName.toLowerCase()}`,
`${firstName[0].toLowerCase()}${lastName.toLowerCase()}`,
`${firstName.toLowerCase()}${lastName[0].toLowerCase()}`,
`${firstName.toLowerCase()}_${lastName.toLowerCase()}`,
];
const username = patterns[Math.floor(Math.random() * patterns.length)];
return `${username}@${domain}`;
}
console.log('Name-based:', emailFromName('John', 'Doe'));
// Generate Test Email with Timestamp
function testEmail(domain = 'example.test') {
const timestamp = Date.now();
const random = Math.floor(Math.random() * 9000) + 1000;
return `test_${timestamp}_${random}@${domain}`;
}
console.log('Test Email:', testEmail());
// Generate Multiple Unique Emails
function generateEmails(count, domain = 'example.com') {
return Array.from({ length: count }, (_, i) =>
`user${Date.now()}${i}@${domain}`
);
}
console.log('Multiple Emails:', generateEmails(3));
// Validate Email Format (Basic)
function isValidEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
const email = randomEmail();
console.log('Valid:', isValidEmail(email) ? 'Yes' : 'No');
// Using crypto for more random usernames (Node.js)
// const crypto = require('crypto');
// function cryptoEmail(domain = 'example.com') {
// const username = crypto.randomBytes(8).toString('hex');
// return `${username}@${domain}`;
// }
How it works in JavaScript
JavaScript generates random emails using Math.random() for usernames combined with domain names. toString(36) converts numbers to alphanumeric strings for readable usernames. For unique emails, use Date.now() for timestamp-based uniqueness. Array.from() creates multiple emails efficiently. Name-based patterns use template literals and string methods. For Node.js, crypto.randomBytes() provides cryptographically secure random usernames. Basic email validation uses regex, but for production use libraries like validator.js.
Sample output
Random Email: [email protected] Custom Domain: [email protected] Readable Email: [email protected] Name-based: [email protected] Test Email: [email protected] Multiple Emails: [ '[email protected]', '[email protected]', '[email protected]' ] Valid: Yes
JavaScript notes
Math.random().toString(36).substring(2, 15)varies in length;crypto.randomUUID()(browsers, Node 19+ as a global) gives a fixed-length, secure alternative.- Jest and Playwright run tests in parallel workers: add
process.env.JEST_WORKER_IDortestInfo.workerIndexto timestamp-based addresses. - In @faker-js/faker,
faker.internet.email()uses real free-mail domains such as gmail.com;faker.internet.exampleEmail()stays on the reserved example domains. - Browsers validate
<input type="email">with the WHATWG pattern, which is stricter than RFC 5322 (no quoted local parts).
Random Email Address Code Examples in Python
Generate random email addresses in Python for testing, QA, and data generation with Faker library and custom patterns.
import random
import string
import time
# Generate Random Email with Random Username
def random_email(domain='example.com'):
username = ''.join(random.choices(string.ascii_lowercase + string.digits, k=12))
return f"{username}@{domain}"
print(f"Random Email: {random_email()}")
print(f"Custom Domain: {random_email('example.org')}")
# Generate Email with Readable Username
def readable_email(domain='example.com'):
adjectives = ['happy', 'sunny', 'clever', 'bright', 'quick']
nouns = ['panda', 'tiger', 'eagle', 'dolphin', 'falcon']
username = f"{random.choice(adjectives)}{random.choice(nouns)}{random.randint(100, 999)}"
return f"{username}@{domain}"
print(f"Readable Email: {readable_email()}")
# Generate Email from Name Pattern
def email_from_name(first_name, last_name, domain='example.net'):
patterns = [
f"{first_name.lower()}.{last_name.lower()}",
f"{first_name[0].lower()}{last_name.lower()}",
f"{first_name.lower()}{last_name[0].lower()}",
f"{first_name.lower()}_{last_name.lower()}",
]
username = random.choice(patterns)
return f"{username}@{domain}"
print(f"Name-based: {email_from_name('John', 'Doe')}")
# Generate Test Email with Timestamp
def test_email(domain='example.test'):
timestamp = int(time.time())
random_num = random.randint(1000, 9999)
return f"test_{timestamp}_{random_num}@{domain}"
print(f"Test Email: {test_email()}")
# Generate Multiple Unique Emails
def generate_emails(count, domain='example.com'):
return [f"user{int(time.time())}{i}@{domain}" for i in range(count)]
print(f"Multiple Emails: {generate_emails(3)}")
# Validate Email Format (Basic)
import re
def is_valid_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
email = random_email()
print(f"Valid: {'Yes' if is_valid_email(email) else 'No'}")
# Using Faker library (pip install faker)
# from faker import Faker
# fake = Faker()
#
# print(f"Faker Email: {fake.email()}")
# print(f"Faker Free Email: {fake.free_email()}") # gmail, yahoo, etc.
# print(f"Faker Company Email: {fake.company_email()}")
# print(f"Faker Safe Email: {fake.safe_email()}") # .example domains
How it works in Python
Python's random.choices() generates random strings from character sets. Combine string.ascii_lowercase with string.digits for alphanumeric usernames. Use time.time() for timestamp-based unique emails. List comprehensions create multiple emails efficiently. For name-based emails, use f-strings with str.lower(). The re module provides regex email validation. For production use, pip install faker and use Faker() which provides email(), free_email(), company_email(), and safe_email() methods with proper formatting.
Sample output
Random Email: [email protected] Custom Domain: [email protected] Readable Email: [email protected] Name-based: [email protected] Test Email: [email protected] Multiple Emails: ['[email protected]', '[email protected]', '[email protected]'] Valid: Yes
Python notes
random.choices()(Python 3.6+) is not secure; usesecrets.token_hex(8)when the address must be unguessable.- Faker's
fake.email()uses example.com, .net and .org by default (safe=True);fake.unique.email()never repeats within one Faker instance. - The
email-validatorpackage checks syntax properly and can also look up the domain's DNS records.
Random Email Address Code Examples in Java
Generate random email addresses in Java for testing, QA, and mock data with JavaFaker library and custom patterns.
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class EmailGenerator {
private static final Random random = new Random();
private static final String[] ADJECTIVES = {"happy", "sunny", "clever", "bright", "quick"};
private static final String[] NOUNS = {"panda", "tiger", "eagle", "dolphin", "falcon"};
public static void main(String[] args) {
// Random Email
System.out.println("Random Email: " + randomEmail("example.com"));
// Readable Email
System.out.println("Readable Email: " + readableEmail("example.com"));
// Name-based Email
System.out.println("Name-based: " + emailFromName("John", "Doe", "example.net"));
// Test Email
System.out.println("Test Email: " + testEmail("example.test"));
// Multiple Emails
List<String> emails = generateEmails(3, "example.com");
System.out.println("Multiple Emails: " + emails);
// Validate
String email = randomEmail("example.com");
System.out.println("Valid: " + (isValidEmail(email) ? "Yes" : "No"));
}
public static String randomEmail(String domain) {
String username = generateRandomString(12);
return username + "@" + domain;
}
public static String readableEmail(String domain) {
String adj = ADJECTIVES[random.nextInt(ADJECTIVES.length)];
String noun = NOUNS[random.nextInt(NOUNS.length)];
int num = random.nextInt(900) + 100;
return adj + noun + num + "@" + domain;
}
public static String emailFromName(String firstName, String lastName, String domain) {
String[] patterns = {
firstName.toLowerCase() + "." + lastName.toLowerCase(),
firstName.substring(0, 1).toLowerCase() + lastName.toLowerCase(),
firstName.toLowerCase() + lastName.substring(0, 1).toLowerCase(),
firstName.toLowerCase() + "_" + lastName.toLowerCase()
};
String username = patterns[random.nextInt(patterns.length)];
return username + "@" + domain;
}
public static String testEmail(String domain) {
long timestamp = System.currentTimeMillis() / 1000;
int randomNum = random.nextInt(9000) + 1000;
return "test_" + timestamp + "_" + randomNum + "@" + domain;
}
public static List<String> generateEmails(int count, String domain) {
List<String> emails = new ArrayList<>();
long baseTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
emails.add("user" + baseTime + i + "@" + domain);
}
return emails;
}
public static boolean isValidEmail(String email) {
String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
return email.matches(regex);
}
private static String generateRandomString(int length) {
String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(chars.charAt(random.nextInt(chars.length())));
}
return sb.toString();
}
// Using JavaFaker (add dependency: com.github.javafaker:javafaker:1.0.2)
// import com.github.javafaker.Faker;
// Faker faker = new Faker();
// String email = faker.internet().emailAddress();
// String safeEmail = faker.internet().safeEmailAddress();
}
How it works in Java
Java generates random emails using Random for number generation and StringBuilder for string construction. System.currentTimeMillis() provides timestamp-based uniqueness. Arrays store word lists for readable emails. Name-based patterns use String.toLowerCase() and substring(). String.matches() validates email format with regex. For production use, add JavaFaker dependency (com.github.javafaker:javafaker) which provides faker.internet().emailAddress() and safeEmailAddress() methods with proper formatting.
Sample output
Random Email: [email protected] Readable Email: [email protected] Name-based: [email protected] Test Email: [email protected] Multiple Emails: [[email protected], [email protected], [email protected]] Valid: Yes
Java notes
- A shared
java.util.Randomis thread-safe but contended; useThreadLocalRandom.current()in parallel tests andSecureRandomfor tokens. - JavaFaker 1.0.2 is no longer maintained; its fork Datafaker (
net.datafaker) keepsinternet().safeEmailAddress(). String.matches()compiles the pattern on every call; keep a staticPattern, or use Apache CommonsEmailValidator.
Random Email Address Code Examples in C#
Generate random email addresses in C# for testing, QA, and mock data with Bogus library and custom patterns.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
class EmailGenerator
{
private static readonly Random random = new Random();
private static readonly string[] Adjectives = { "happy", "sunny", "clever", "bright", "quick" };
private static readonly string[] Nouns = { "panda", "tiger", "eagle", "dolphin", "falcon" };
static void Main()
{
// Random Email
Console.WriteLine($"Random Email: {RandomEmail("example.com")}");
// Readable Email
Console.WriteLine($"Readable Email: {ReadableEmail("example.com")}");
// Name-based Email
Console.WriteLine($"Name-based: {EmailFromName("John", "Doe", "example.net")}");
// Test Email
Console.WriteLine($"Test Email: {TestEmail("example.test")}");
// Multiple Emails
var emails = GenerateEmails(3, "example.com");
Console.WriteLine($"Multiple Emails: {string.Join(", ", emails)}");
// Validate
string email = RandomEmail("example.com");
Console.WriteLine($"Valid: {(IsValidEmail(email) ? "Yes" : "No")}");
}
public static string RandomEmail(string domain = "example.com")
{
string username = GenerateRandomString(12);
return $"{username}@{domain}";
}
public static string ReadableEmail(string domain = "example.com")
{
string adj = Adjectives[random.Next(Adjectives.Length)];
string noun = Nouns[random.Next(Nouns.Length)];
int num = random.Next(100, 1000);
return $"{adj}{noun}{num}@{domain}";
}
public static string EmailFromName(string firstName, string lastName, string domain = "example.net")
{
string[] patterns = {
$"{firstName.ToLower()}.{lastName.ToLower()}",
$"{firstName[0].ToString().ToLower()}{lastName.ToLower()}",
$"{firstName.ToLower()}{lastName[0].ToString().ToLower()}",
$"{firstName.ToLower()}_{lastName.ToLower()}"
};
string username = patterns[random.Next(patterns.Length)];
return $"{username}@{domain}";
}
public static string TestEmail(string domain = "example.test")
{
long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
int randomNum = random.Next(1000, 10000);
return $"test_{timestamp}_{randomNum}@{domain}";
}
public static List<string> GenerateEmails(int count, string domain = "example.com")
{
long baseTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
return Enumerable.Range(0, count)
.Select(i => $"user{baseTime}{i}@{domain}")
.ToList();
}
public static bool IsValidEmail(string email)
{
string pattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
return Regex.IsMatch(email, pattern);
}
private static string GenerateRandomString(int length)
{
const string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
return new string(Enumerable.Range(0, length)
.Select(_ => chars[random.Next(chars.Length)])
.ToArray());
}
// Using Bogus library (Install-Package Bogus)
// using Bogus;
// var faker = new Faker();
// string email = faker.Internet.Email();
// string exampleEmail = faker.Internet.ExampleEmail();
// string companyEmail = faker.Internet.Email(provider: "example.net");
}
How it works in C#
C# uses Random for number generation and LINQ for collection operations. DateTimeOffset.UtcNow.ToUnixTimeSeconds() provides timestamp-based uniqueness. String interpolation with $"" creates clean email formats. Enumerable.Range() with Select() generates multiple emails efficiently. Regex.IsMatch() validates email format. For production, install Bogus NuGet package (Install-Package Bogus) which provides faker.Internet.Email(), ExampleEmail(), and customizable email generation with proper formatting.
Sample output
Random Email: [email protected] Readable Email: [email protected] Name-based: [email protected] Test Email: [email protected] Multiple Emails: [email protected], [email protected], [email protected] Valid: Yes
C# notes
MailAddress.TryCreate()(.NET 5+) parses addresses, but it also accepts display-name forms likeJohn <[email protected]>: compare itsAddressproperty.Random.Shared(.NET 6+) is thread-safe;RandomNumberGenerator.GetString(chars, 12)(.NET 8) builds a secure username in one call.- In Bogus,
Internet.ExampleEmail()uses the reserved example domains, whileInternet.Email()picks real free-mail providers.
Random Email Address Code Examples in C++
Generate random email addresses in C++ using modern C++11/17 features for testing, QA, and mock data generation.
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
#include <cctype>
class EmailGenerator {
private:
std::random_device rd;
std::mt19937 gen;
std::uniform_int_distribution<> dist;
static constexpr const char* adjectives[] = {"happy", "sunny", "clever", "bright", "quick"};
static constexpr const char* nouns[] = {"panda", "tiger", "eagle", "dolphin", "falcon"};
public:
EmailGenerator() : gen(rd()), dist(0, 9) {}
std::string randomEmail(const std::string& domain = "example.com") {
std::string username = generateRandomString(12);
return username + "@" + domain;
}
std::string readableEmail(const std::string& domain = "example.com") {
std::uniform_int_distribution<> adj_dist(0, 4);
std::uniform_int_distribution<> noun_dist(0, 4);
std::uniform_int_distribution<> num_dist(100, 999);
std::string adj = adjectives[adj_dist(gen)];
std::string noun = nouns[noun_dist(gen)];
int num = num_dist(gen);
return adj + noun + std::to_string(num) + "@" + domain;
}
std::string emailFromName(const std::string& firstName,
const std::string& lastName,
const std::string& domain = "example.net") {
std::vector<std::string> patterns = {
toLowerCase(firstName) + "." + toLowerCase(lastName),
std::string(1, std::tolower(firstName[0])) + toLowerCase(lastName),
toLowerCase(firstName) + std::string(1, std::tolower(lastName[0])),
toLowerCase(firstName) + "_" + toLowerCase(lastName)
};
std::uniform_int_distribution<> pattern_dist(0, patterns.size() - 1);
return patterns[pattern_dist(gen)] + "@" + domain;
}
std::string testEmail(const std::string& domain = "example.test") {
auto timestamp = std::chrono::system_clock::now().time_since_epoch().count();
std::uniform_int_distribution<> num_dist(1000, 9999);
return "test_" + std::to_string(timestamp) + "_" +
std::to_string(num_dist(gen)) + "@" + domain;
}
std::vector<std::string> generateEmails(int count,
const std::string& domain = "example.com") {
std::vector<std::string> emails;
auto baseTime = std::chrono::system_clock::now().time_since_epoch().count();
for (int i = 0; i < count; ++i) {
emails.push_back("user" + std::to_string(baseTime + i) + "@" + domain);
}
return emails;
}
bool isValidEmail(const std::string& email) {
// Basic validation: contains @ and .
size_t at_pos = email.find('@');
size_t dot_pos = email.rfind('.');
return at_pos != std::string::npos &&
dot_pos != std::string::npos &&
at_pos < dot_pos &&
dot_pos < email.length() - 1;
}
private:
std::string generateRandomString(int length) {
const std::string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
std::uniform_int_distribution<> char_dist(0, chars.length() - 1);
std::string result;
for (int i = 0; i < length; ++i) {
result += chars[char_dist(gen)];
}
return result;
}
std::string toLowerCase(const std::string& str) {
std::string result = str;
std::transform(result.begin(), result.end(), result.begin(), ::tolower);
return result;
}
};
int main() {
EmailGenerator generator;
std::cout << "Random Email: " << generator.randomEmail() << std::endl;
std::cout << "Readable Email: " << generator.readableEmail() << std::endl;
std::cout << "Name-based: " << generator.emailFromName("John", "Doe") << std::endl;
std::cout << "Test Email: " << generator.testEmail() << std::endl;
auto emails = generator.generateEmails(3);
std::cout << "Multiple Emails: ";
for (const auto& email : emails) {
std::cout << email << " ";
}
std::cout << std::endl;
std::string email = generator.randomEmail();
std::cout << "Valid: " << (generator.isValidEmail(email) ? "Yes" : "No") << std::endl;
return 0;
}
How it works in C++
Modern C++ uses std::random_device and std::mt19937 for high-quality random generation. std::uniform_int_distribution generates uniformly distributed integers for indices and numbers. std::chrono provides timestamp-based uniqueness with time_since_epoch(). std::transform with ::tolower converts strings to lowercase. std::vector stores multiple emails efficiently. Basic email validation checks for @ and . positions. For regex validation, use <regex> header with std::regex and std::regex_match().
Sample output
Random Email: [email protected] Readable Email: [email protected] Name-based: [email protected] Test Email: [email protected] Multiple Emails: [email protected] [email protected] [email protected] Valid: Yes
C++ notes
- The in-class
static constexpr const char* adjectives[]needs C++17 (implicitly inline); under C++11/14 it fails to link once it is indexed. - Pass
static_cast<unsigned char>(c)tostd::tolower: a negativecharfrom a non-ASCII name is undefined behavior. - The unit of
system_clock::now().time_since_epoch().count()depends on the library (nanoseconds in libstdc++, microseconds in libc++); useduration_castfor portable timestamps.
Random Email Address Code Examples in Ruby
Generate random email addresses in Ruby for testing, QA, and mock data with Faker gem and custom patterns.
# Generate Random Email with Random Username
def random_email(domain = 'example.com')
username = (0...12).map { ('a'..'z').to_a.concat(('0'..'9').to_a).sample }.join
"#{username}@#{domain}"
end
puts "Random Email: #{random_email}"
puts "Custom Domain: #{random_email('example.org')}"
# Generate Email with Readable Username
def readable_email(domain = 'example.com')
adjectives = %w[happy sunny clever bright quick]
nouns = %w[panda tiger eagle dolphin falcon]
adj = adjectives.sample
noun = nouns.sample
num = rand(100..999)
"#{adj}#{noun}#{num}@#{domain}"
end
puts "Readable Email: #{readable_email}"
# Generate Email from Name Pattern
def email_from_name(first_name, last_name, domain = 'example.net')
patterns = [
"#{first_name.downcase}.#{last_name.downcase}",
"#{first_name[0].downcase}#{last_name.downcase}",
"#{first_name.downcase}#{last_name[0].downcase}",
"#{first_name.downcase}_#{last_name.downcase}"
]
username = patterns.sample
"#{username}@#{domain}"
end
puts "Name-based: #{email_from_name('John', 'Doe')}"
# Generate Test Email with Timestamp
def test_email(domain = 'example.test')
timestamp = Time.now.to_i
random_num = rand(1000..9999)
"test_#{timestamp}_#{random_num}@#{domain}"
end
puts "Test Email: #{test_email}"
# Generate Multiple Unique Emails
def generate_emails(count, domain = 'example.com')
base_time = Time.now.to_i
count.times.map { |i| "user#{base_time}#{i}@#{domain}" }
end
puts "Multiple Emails: #{generate_emails(3).inspect}"
# Validate Email Format (Basic)
def valid_email?(email)
email.match?(/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i)
end
email = random_email
puts "Valid: #{valid_email?(email) ? 'Yes' : 'No'}"
# Using Faker gem (gem install faker)
# require 'faker'
#
# puts "Faker Email: #{Faker::Internet.email}"
# puts "Faker Example Email: #{Faker::Internet.email(domain: 'example.com')}" # free_email and safe_email no longer exist in current Faker
# puts "Faker Username: #{Faker::Internet.username}@example.com"
#
# # Custom domain
# puts "Custom: #{Faker::Internet.email(domain: 'example.net')}"
#
# # Name-based email
# first = Faker::Name.first_name
# last = Faker::Name.last_name
# puts "Name Email: #{Faker::Internet.email(name: "#{first} #{last}")}"
How it works in Ruby
Ruby generates random emails using Array#sample for random selection and rand() for numbers. String interpolation with #{} creates clean email formats. Time.now.to_i provides Unix timestamp for uniqueness. times.map generates multiple emails efficiently. String#match? validates with regex. For production, gem install faker and use Faker::Internet whose Faker::Internet.email accepts name: and domain: options; current versions default to reserved .test domains and no longer have free_email or safe_email.
Sample output
Random Email: [email protected] Custom Domain: [email protected] Readable Email: [email protected] Name-based: [email protected] Test Email: [email protected] Multiple Emails: ["[email protected]", "[email protected]", "[email protected]"] Valid: Yes
Ruby notes
Array#sampleandranduse Mersenne Twister;SecureRandom.alphanumeric(12).downcasegives a secure username.URI::MailTo::EMAIL_REGEXPis the standard library's address pattern, the one Rails apps usually pass tovalidates :email, format:.- Current faker-ruby builds
Faker::Internet.emailon reserved.testdomains by default;Faker::Internet.unique.emailavoids repeats.
Random Email Address Code Examples in Go
Generate random email addresses in Go using math/rand package for testing, QA, and mock data generation.
package main
import (
"fmt"
"math/rand"
"strings"
"time"
"regexp"
)
var (
adjectives = []string{"happy", "sunny", "clever", "bright", "quick"}
nouns = []string{"panda", "tiger", "eagle", "dolphin", "falcon"}
)
func main() {
// Random Email
fmt.Println("Random Email:", randomEmail("example.com"))
// Readable Email
fmt.Println("Readable Email:", readableEmail("example.com"))
// Name-based Email
fmt.Println("Name-based:", emailFromName("John", "Doe", "example.net"))
// Test Email
fmt.Println("Test Email:", testEmail("example.test"))
// Multiple Emails
emails := generateEmails(3, "example.com")
fmt.Println("Multiple Emails:", emails)
// Validate
email := randomEmail("example.com")
fmt.Printf("Valid: %s\n", boolToYesNo(isValidEmail(email)))
}
func randomEmail(domain string) string {
username := generateRandomString(12)
return fmt.Sprintf("%s@%s", username, domain)
}
func readableEmail(domain string) string {
adj := adjectives[rand.Intn(len(adjectives))]
noun := nouns[rand.Intn(len(nouns))]
num := rand.Intn(900) + 100
return fmt.Sprintf("%s%s%d@%s", adj, noun, num, domain)
}
func emailFromName(firstName, lastName, domain string) string {
patterns := []string{
fmt.Sprintf("%s.%s", strings.ToLower(firstName), strings.ToLower(lastName)),
fmt.Sprintf("%c%s", strings.ToLower(firstName)[0], strings.ToLower(lastName)),
fmt.Sprintf("%s%c", strings.ToLower(firstName), strings.ToLower(lastName)[0]),
fmt.Sprintf("%s_%s", strings.ToLower(firstName), strings.ToLower(lastName)),
}
username := patterns[rand.Intn(len(patterns))]
return fmt.Sprintf("%s@%s", username, domain)
}
func testEmail(domain string) string {
timestamp := time.Now().Unix()
randomNum := rand.Intn(9000) + 1000
return fmt.Sprintf("test_%d_%d@%s", timestamp, randomNum, domain)
}
func generateEmails(count int, domain string) []string {
emails := make([]string, count)
baseTime := time.Now().UnixNano()
for i := 0; i < count; i++ {
emails[i] = fmt.Sprintf("user%d%d@%s", baseTime, i, domain)
}
return emails
}
func isValidEmail(email string) bool {
// Basic regex validation
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
matched, _ := regexp.MatchString(pattern, email)
return matched
}
func generateRandomString(length int) string {
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
result := make([]byte, length)
for i := range result {
result[i] = chars[rand.Intn(len(chars))]
}
return string(result)
}
func boolToYesNo(b bool) string {
if b {
return "Yes"
}
return "No"
}
How it works in Go
Go uses math/rand package for random generation. Since Go 1.20 the global source is seeded automatically, so no rand.Seed call is needed. rand.Intn() generates random indices for array access. time.Now().Unix() provides Unix timestamp for uniqueness. strings.ToLower() converts strings to lowercase. fmt.Sprintf() formats strings with clean syntax. regexp.MatchString() validates email format. Use make([]string, count) to preallocate slices. For byte slice to string conversion, use string(bytes).
Sample output
Random Email: [email protected] Readable Email: [email protected] Name-based: [email protected] Test Email: [email protected] Multiple Emails: [[email protected] [email protected] [email protected]] Valid: Yes
Go notes
- The top-level
math/randfunctions are safe for concurrent use; a*rand.Randfromrand.Newis not, so do not share one across goroutines. net/mail.ParseAddressparses RFC 5322 addresses, including display names; compare the returnedAddressfield.- For an unguessable local part, use
crypto/rand: Go 1.24 addsrand.Text(), a 26-character base32 string with 128 random bits.
Try the Interactive Generator
Need values right now rather than code? The Email address generator runs in the browser and exports to TXT, CSV or JSON.
OPEN THE EMAIL ADDRESS GENERATOR →