### Install SimpleJavaMail Karaf Feature Source: https://github.com/bbottema/simple-java-mail/blob/master/modules/karaf-module/README.md After adding the repository, use this command to install the SimpleJavaMail feature. This makes the library available for use within your Karaf applications. ```bash karaf@root()> feature:install simplejavamail-karaf-feature ``` -------------------------------- ### Configure Mailer with OAuth2 Authentication Source: https://context7.com/bbottema/simple-java-mail/llms.txt Configure a Mailer instance for SMTP with OAuth2 authentication, demonstrated with a Gmail example. ```java import org.simplejavamail.mailer.MailerBuilder; import org.simplejavamail.api.mailer.Mailer; import org.simplejavamail.api.mailer.config.TransportStrategy; // OAuth2 authentication (Gmail example) Mailer mailerOAuth2 = MailerBuilder .withSMTPServer("smtp.gmail.com", 587, "user@gmail.com", oauthToken) .withTransportStrategy(TransportStrategy.SMTP_OAUTH2) .buildMailer(); ``` -------------------------------- ### Build Mailer from Configuration File Source: https://context7.com/bbottema/simple-java-mail/llms.txt Build a Mailer instance by loading configuration from a `simplejavamail.properties` file located on the classpath. ```java import org.simplejavamail.mailer.MailerBuilder; import org.simplejavamail.api.mailer.Mailer; // Build from config file only (simplejavamail.properties on classpath) Mailer mailerFromConfig = MailerBuilder.buildMailer(); ``` -------------------------------- ### Import GPG Key Source: https://github.com/bbottema/simple-java-mail/blob/master/how to release.txt Import an existing GPG key for signing artifacts. Ensure the keyring file is correctly specified. ```bash gpg --allow-secret-key-import --import .gpg ``` -------------------------------- ### Configuring PKCS12 Keystores for S/MIME in Java Source: https://context7.com/bbottema/simple-java-mail/llms.txt Shows how to configure PKCS12 keystores for S/MIME signing and decryption using Pkcs12Config. Supports loading from file paths, File objects, InputStreams, and byte arrays. ```java import org.simplejavamail.api.mailer.config.Pkcs12Config; import java.io.File; import java.io.FileInputStream; // From a file path Pkcs12Config fromPath = Pkcs12Config.builder() .pkcs12Store("/certs/my-keystore.p12") .storePassword("storePass".toCharArray()) .keyAlias("myKey") .keyPassword("keyPass".toCharArray()) .build(); // From a File object Pkcs12Config fromFile = Pkcs12Config.builder() .pkcs12Store(new File("my-keystore.p12")) .storePassword("storePass".toCharArray()) .keyAlias("myKey") .keyPassword("keyPass".toCharArray()) .build(); // From an InputStream Pkcs12Config fromStream = Pkcs12Config.builder() .pkcs12Store(new FileInputStream("my-keystore.p12")) .storePassword("storePass".toCharArray()) .keyAlias("myKey") .keyPassword("keyPass".toCharArray()) .build(); // From a byte array byte[] keystoreBytes = Files.readAllBytes(Paths.get("my-keystore.p12")); Pkcs12Config fromBytes = Pkcs12Config.builder() .pkcs12Store(keystoreBytes) .storePassword("storePass".toCharArray()) .keyAlias("myKey") .keyPassword("keyPass".toCharArray()) .build(); ``` -------------------------------- ### Create Email using Fluent Builder Interface Source: https://github.com/bbottema/simple-java-mail/wiki/Manual Illustrates constructing an email object using a fluent builder pattern. This approach allows for a more readable and chained method call syntax for setting email properties. ```java Email email = new Email.Builder() .from("lollypop", "lolly.pop@somemail.com") .to("C. Cane", "candycane@candyshop.org") .to("C. Bo", "chocobo@candyshop.org") .subject("hey") .text("We should meet up! ;)") .build(); ``` -------------------------------- ### Export Certificate to PKCS12 Format Source: https://github.com/bbottema/simple-java-mail/blob/master/modules/simple-java-mail/src/test/resources/pkcs12/how-to.html Use this command to bundle your certificate (smime_test_user.crt) and private key (smime_test_user.key) into a PKCS12 file (smime_test_user.p12). You will be prompted to enter pass phrases for your private key and the new PKCS12 file. ```bash openssl pkcs12 -export -in smime_test_user.crt -inkey smime_test_user.key -out smime_test_user.p12 ``` -------------------------------- ### Manual Release with Maven Source: https://github.com/bbottema/simple-java-mail/blob/master/how to release.txt Perform a manual release of the library using Maven. This command deploys the artifact after cleaning and building. ```bash mvn -DperformRelease=true clean deploy ``` -------------------------------- ### Constructing and Using Recipient Objects in Java Source: https://context7.com/bbottema/simple-java-mail/llms.txt Demonstrates how to create Recipient objects with display names and types, and how to use them with the EmailBuilder. Inspecting recipients on a built email is also shown. ```java import org.simplejavamail.api.email.Recipient; import jakarta.mail.Message.RecipientType; // Create recipients directly Recipient to = new Recipient("Alice Smith", "alice@example.com", RecipientType.TO); Recipient cc = new Recipient("Bob Jones", "bob@example.com", RecipientType.CC); Recipient bcc = new Recipient(null, "audit@example.com", RecipientType.BCC); // Use them in the builder Email email = EmailBuilder.startingBlank() .from("sender@example.com") .withRecipients(to, cc, bcc) .withSubject("Using Recipient objects") .withPlainText("Demonstrating explicit Recipient construction.") .buildEmail(); // Inspect recipients on a built email email.getToRecipients().forEach(r -> System.out.println("TO: " + r.getName() + " <" + r.getAddress() + ">")); email.getCcRecipients().forEach(r -> System.out.println("CC: " + r.getAddress())); ``` -------------------------------- ### Set SMTP Server for Development Source: https://github.com/bbottema/simple-java-mail/wiki/Manual When running tests or developing, provide JVM arguments to specify the SMTP server details. ```bash java -Dhost=smtp.someserver.com -Dport=25 -Dusername=joe -Dpassword=sixpack ``` -------------------------------- ### OpenSSL PKCS12 Export Prompts Source: https://github.com/bbottema/simple-java-mail/blob/master/modules/simple-java-mail/src/test/resources/pkcs12/how-to.html This shows the expected prompts when executing the openssl pkcs12 -export command. You will need to enter the pass phrase for your private key and then set a new pass phrase for the PKCS12 file. ```text Loading 'screen' into random state - done Enter pass phrase for smime_test_user.key: Enter Export Password: Verifying - Enter Export Password: ``` -------------------------------- ### Send Email with Attachments and Embedded Images Source: https://github.com/bbottema/simple-java-mail/wiki/Manual Demonstrates creating and sending an email with recipients, text content, HTML content, embedded images, and attachments. Requires setting up a Mailer instance with SMTP host, port, username, and password. ```java final Email email = new Email(); email.setFromAddress("lollypop", "lolly.pop@somemail.com"); email.setSubject("hey"); email.addRecipient("C. Cane", "candycane@candyshop.org", RecipientType.TO); email.addRecipient("C. Bo", "chocobo@candyshop.org", RecipientType.BCC); email.setText("We should meet up! ;)"); email.setTextHTML("We should meet up!"); // embed images and include downloadable attachments email.addEmbeddedImage("wink1", imageByteArray, "image/png"); email.addEmbeddedImage("wink2", imageDatesource); email.addAttachment("invitation", pdfByteArray, "application/pdf"); email.addAttachment("dresscode", odfDatasource); new Mailer("smtp.host.com", 25, "username", "password").sendMail(email); ``` -------------------------------- ### Export PKCS12 Keystore with RSA Key Source: https://github.com/bbottema/simple-java-mail/blob/master/modules/simple-java-mail/src/test/resources/pkcs12/about all this.txt Command to export a PKCS12 keystore with an RSA private key from a PEM certificate and key. Use 'letmein' as the password. ```bash openssl pkcs12 -export -in smime_test_user.pem.crt -inkey smime_test_user.key -out smime_keystore.pkcs12 -name smime_test_user_alias_rsa -noiter -nomaciter ``` -------------------------------- ### Add SimpleJavaMail Karaf Feature Source: https://github.com/bbottema/simple-java-mail/blob/master/modules/karaf-module/README.md Use this command to add the SimpleJavaMail Karaf feature repository to your Karaf instance. Replace with the actual version of simplejavamail. ```bash karaf@root()> repo-add mvn:org.simplejavamail/simplejavamail-karaf-feature//xml/features ``` -------------------------------- ### Configure Mailer with SMTP TLS Source: https://context7.com/bbottema/simple-java-mail/llms.txt Configure a Mailer instance for SMTP with STARTTLS on port 587. Includes session timeout and debug logging settings. ```java import org.simplejavamail.mailer.MailerBuilder; import org.simplejavamail.api.mailer.Mailer; import org.simplejavamail.api.mailer.config.TransportStrategy; // SMTP with STARTTLS (port 587) Mailer mailerTLS = MailerBuilder .withSMTPServer("smtp.example.com", 587, "user@example.com", "password") .withTransportStrategy(TransportStrategy.SMTP_TLS) .withSessionTimeout(10_000) .withDebugLogging(false) .buildMailer(); ``` -------------------------------- ### Maven Settings.xml Server Configuration Source: https://github.com/bbottema/simple-java-mail/blob/master/how to release.txt Configure the 'ossrh' server in Maven's settings.xml to provide credentials for deploying to Sonatype's OSS Repository. ```xml ossrh sonatype user sonatype password ``` -------------------------------- ### Send Email using a Preconfigured Mail Session Source: https://github.com/bbottema/simple-java-mail/wiki/Manual Shows how to send an email using a Mailer instance initialized with an existing JavaMail Session object. This is useful for integrating with existing mail configurations. ```java new Mailer(yourSession).sendMail(email); ``` -------------------------------- ### Send Email using SSL/TLS Transport Strategy Source: https://github.com/bbottema/simple-java-mail/wiki/Manual Demonstrates configuring the Mailer to use SSL or TLS for secure email transmission. Two common transport strategies, SMTP_SSL and SMTP_TLS, are shown. ```java new Mailer("smtp.host.com", 25, "username", "password", TransportStrategy.SMTP_SSL).sendMail(email); new Mailer("smtp.host.com", 25, "username", "password", TransportStrategy.SMTP_TLS).sendMail(email); ``` -------------------------------- ### OpenSSL Configuration for S/MIME Certificate Source: https://github.com/bbottema/simple-java-mail/blob/master/modules/simple-java-mail/src/test/resources/pkcs12/how-to.html This configuration file defines the necessary extensions for creating an S/MIME certificate. Ensure the [req] and [req_distinguished_name] sections are present to avoid errors. ```ini [req] distinguished_name = req_distinguished_name [req_distinguished_name] countryName = Country Name (2 letter code) countryName_default = AU countryName_min = 2 countryName_max = 2 stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = Some-State localityName = Locality Name (eg, city) 0.organizationName = Organization Name (eg, company) 0.organizationName_default = Internet Widgits Pty Ltd organizationalUnitName = Organizational Unit Name (eg, section) commonName = Common Name (e.g. server FQDN or YOUR name) commonName_max = 64 emailAddress = Email Address emailAddress_max = 40 [smime] basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectKeyIdentifier = hash authorityKeyIdentifier = keyid,issuer subjectAltName = email:copy extendedKeyUsage = emailProtection ``` -------------------------------- ### Configure Mailer with SMTPS Source: https://context7.com/bbottema/simple-java-mail/llms.txt Configure a Mailer instance for SMTP over SSL (SMTPS) on port 465. ```java import org.simplejavamail.mailer.MailerBuilder; import org.simplejavamail.api.mailer.Mailer; import org.simplejavamail.api.mailer.config.TransportStrategy; // SMTP over SSL (port 465) Mailer mailerSSL = MailerBuilder .withSMTPServer("smtp.example.com", 465, "user@example.com", "password") .withTransportStrategy(TransportStrategy.SMTPS) .buildMailer(); ``` -------------------------------- ### Async Batch Processing with Connection Pool Source: https://context7.com/bbottema/simple-java-mail/llms.txt Configure a mailer cluster for high-throughput sending using a persistent SMTP connection pool. Multiple mailers with the same clusterKey form a cluster for load-balanced sending. Ensure the batch-module is on the classpath. ```java import org.simplejavamail.mailer.MailerBuilder; import org.simplejavamail.api.mailer.Mailer; import org.simplejavamail.api.mailer.config.LoadBalancingStrategy; import org.simplejavamail.api.mailer.config.TransportStrategy; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.List; import java.util.ArrayList; UUID clusterKey = UUID.randomUUID(); // Primary SMTP server Mailer primary = MailerBuilder .withSMTPServer("smtp-primary.example.com", 587, "user", "pass") .withTransportStrategy(TransportStrategy.SMTP_TLS) .async() .withClusterKey(clusterKey) .withConnectionPoolCoreSize(5) .withConnectionPoolMaxSize(20) .withConnectionPoolClaimTimeoutMillis(5_000) .withConnectionPoolLoadBalancingStrategy(LoadBalancingStrategy.ROUND_ROBIN) .buildMailer(); // Failover SMTP server in the same cluster Mailer failover = MailerBuilder .withSMTPServer("smtp-backup.example.com", 587, "user", "pass") .withTransportStrategy(TransportStrategy.SMTP_TLS) .async() .withClusterKey(clusterKey) .withConnectionPoolCoreSize(2) .withConnectionPoolMaxSize(10) .buildMailer(); // Send 100 emails asynchronously via the cluster List> futures = new ArrayList<>(); for (int i = 0; i < 100; i++) { Email email = EmailBuilder.startingBlank() .from("sender@example.com") .to("recipient" + i + "@example.com") .withSubject("Batch message " + i) .withPlainText("Message " + i) .buildEmail(); futures.add(primary.sendMail(email, true)); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); primary.shutdownConnectionPool().get(); failover.shutdownConnectionPool().get(); ``` -------------------------------- ### Generate Private Key Source: https://github.com/bbottema/simple-java-mail/blob/master/modules/simple-java-mail/src/test/resources/pkcs12/how-to.html Generates a 4096-bit RSA private key. You will be prompted to enter a passphrase for the key. ```bash openssl genrsa -aes256 -out smime_test_user.key 4096 ``` -------------------------------- ### File-Based Configuration with simplejavamail.properties Source: https://context7.com/bbottema/simple-java-mail/llms.txt Externalize builder properties to `simplejavamail.properties` on the classpath. Configuration is resolved in order: system property > environment variable > properties file. ```properties # simplejavamail.properties (place on classpath) # SMTP connection simplejavamail.smtp.host=smtp.example.com simplejavamail.smtp.port=587 simplejavamail.smtp.username=user@example.com simplejavamail.smtp.password=secret simplejavamail.transportstrategy=SMTP_TLS # Proxy (optional) simplejavamail.proxy.host=socks5.proxy.com simplejavamail.proxy.port=1080 simplejavamail.proxy.username=proxyUser simplejavamail.proxy.password=proxyPass simplejavamail.proxy.socks5bridge.port=1081 # Email defaults (applied to all outgoing emails) simplejavamail.defaults.from.name=My App simplejavamail.defaults.from.address=noreply@example.com simplejavamail.defaults.replyto.address=support@example.com simplejavamail.defaults.subject=Hello from My App # DKIM defaults (applied when dkim-module is present) simplejavamail.dkim.signing.private.key.file.or.data=/path/to/private.der simplejavamail.dkim.signing.selector=mail simplejavamail.dkim.signing.signing.domain=example.com # Session / pool settings simplejavamail.session.timeout.millis=30000 simplejavamail.pool.coresize=5 simplejavamail.pool.maxsize=20 simplejavamail.pool.claimtimeout.millis=10000 simplejavamail.pool.expireafter.millis=60000 # Pass-through extra JavaMail session properties simplejavamail.extraproperties.mail.smtp.connectiontimeout=10000 ``` ```java # With the properties file on classpath, build a fully configured mailer with no arguments: import org.simplejavamail.mailer.MailerBuilder; import org.simplejavamail.api.mailer.Mailer; Mailer mailer = MailerBuilder.buildMailer(); mailer.testConnection(); // verifies config is correct ``` -------------------------------- ### Build a Full Email with Attachments and Embedded Images Source: https://context7.com/bbottema/simple-java-mail/llms.txt Use EmailBuilder to construct a comprehensive email. Supports plain text, HTML content, embedded images, attachments, custom headers, and fixing message IDs. Ensure necessary data sources (like byte arrays for images and PDFs) are prepared. ```java import org.simplejavamail.email.EmailBuilder; import org.simplejavamail.api.email.Email; import jakarta.mail.Message.RecipientType; import jakarta.activation.DataSource; import jakarta.mail.util.ByteArrayDataSource; // Build a full email with plain text, HTML, embedded image, and attachment Email email = EmailBuilder.startingBlank() .from("Sender Name", "sender@example.com") .to("Alice", "alice@example.com") .cc("Bob", "bob@example.com") .bcc("bcc@example.com") .withReplyTo("replies@example.com") .withSubject("Hello from Simple Java Mail!") .withPlainText("Hi Alice,\n\nPlease see the attached report.\n\nBest,\nSender") .withHTMLText("

Hi Alice,

Please see the attached report.

") .withEmbeddedImage("logo", new ByteArrayDataSource(logoBytes, "image/png")) .withAttachment("report.pdf", new ByteArrayDataSource(pdfBytes, "application/pdf")) .withHeader("X-Priority", "1") .fixingMessageId("") .buildEmail(); ``` -------------------------------- ### Spring Boot Auto-Configuration for Mailer Source: https://context7.com/bbottema/simple-java-mail/llms.txt Import `SimpleJavaMailSpringSupport` to automatically configure a Mailer bean from `application.properties`. The module reads `simplejavamail.*` properties and provides a `MailerGenericBuilder`. ```java import org.simplejavamail.springsupport.SimpleJavaMailSpringSupport; import org.springframework.context.annotation.Import; import org.springframework.stereotype.Service; import org.simplejavamail.api.mailer.Mailer; import org.simplejavamail.email.EmailBuilder; import org.simplejavamail.api.email.Email; import org.springframework.beans.factory.annotation.Autowired; @Import(SimpleJavaMailSpringSupport.class) // activates auto-configuration @Service public class NotificationService { @Autowired private Mailer mailer; // fully configured from application.properties public void sendWelcomeEmail(String userEmail, String userName) { Email email = EmailBuilder.startingBlank() .to(userName, userEmail) .withSubject("Welcome to Our Service!") .withHTMLText("

Welcome, " + userName + "!

") .withPlainText("Welcome, " + userName + "!") .buildEmail(); mailer.sendMail(email); } } ``` ```properties # application.properties simplejavamail.smtp.host=smtp.example.com simplejavamail.smtp.port=587 simplejavamail.smtp.username=user@example.com simplejavamail.smtp.password=secret simplejavamail.transportstrategy=SMTP_TLS simplejavamail.defaults.from.name=My Application simplejavamail.defaults.from.address=noreply@example.com simplejavamail.defaults.replyto.address=support@example.com simplejavamail.pool.coresize=5 simplejavamail.pool.maxsize=20 simplejavamail.pool.claimtimeout.millis=5000 simplejavamail.session.timeout.millis=10000 ``` -------------------------------- ### Generate PKCS12 Keystore with DSA Key Source: https://github.com/bbottema/simple-java-mail/blob/master/modules/simple-java-mail/src/test/resources/pkcs12/about all this.txt Command to generate a new PKCS12 keystore with a DSA key pair. This command sets up validity, distinguished name, and Subject Alternative Names. ```bash keytool -genkeypair -alias smime_test_user_alias_dsa -keyalg DSA -keysize 2048 -keystore new-temporary-keystore.p12 -storetype PKCS12 -storepass letmein -validity 3650 -dname "EMAILADDRESS=emailaddress, CN=Some Name, O=Simple Java Mail, ST=Province, C=NL" -ext san=dns:simplejavamail.org,dns:www.simplejavamail.org ``` -------------------------------- ### Configure Email Defaults and Overrides Source: https://context7.com/bbottema/simple-java-mail/llms.txt Set default email fields (e.g., FROM) that are applied only if not specified, and overrides that always replace existing fields (e.g., BCC). Also configure maximum email size. ```java import org.simplejavamail.email.EmailBuilder; import org.simplejavamail.api.email.Email; import org.simplejavamail.mailer.MailerBuilder; import org.simplejavamail.api.mailer.Mailer; // Define a defaults email: sets FROM if the email doesn't specify one Email defaults = EmailBuilder.startingBlank() .from("noreply@myapp.com") .withHeader("X-Application", "MyApp/1.0") .buildEmail(); // Define an overrides email: always appends this BCC, even if already set Email overrides = EmailBuilder.startingBlank() .bcc("audit@myapp.com") .buildEmail(); Mailer governedMailer = MailerBuilder .withSMTPServer("smtp.example.com", 587, "user", "pass") .withEmailDefaults(defaults) .withEmailOverrides(overrides) .withMaximumEmailSize(10 * 1024 * 1024) // 10 MB limit .buildMailer(); // This email gets FROM injected from defaults, and BCC added from overrides Email email = EmailBuilder.startingBlank() .to("recipient@example.com") .withSubject("Governed email") .withPlainText("Body text") .buildEmail(); governedMailer.sendMail(email); ``` -------------------------------- ### Export Secret GPG Key for CI/CD Source: https://github.com/bbottema/simple-java-mail/blob/master/how to release.txt Generate an ASCII-armored export of a secret GPG key. This is useful for storing the key as a secret property in CI/CD environments. ```bash gpg --no-default-keyring --armor --secret-keyring ./secring.gpg --keyring ./pubring.gpg --export-secret-key USER > secring.gpg.asc ``` -------------------------------- ### Create Certificate Signing Request (CSR) Source: https://github.com/bbottema/simple-java-mail/blob/master/modules/simple-java-mail/src/test/resources/pkcs12/how-to.html Creates a certificate signing request using the generated private key. You will be prompted to enter the passphrase for the private key and provide details for the certificate. ```bash openssl req -new -key smime_test_user.key -out smime_test_user.csr ``` -------------------------------- ### Add Custom Email Headers Source: https://github.com/bbottema/simple-java-mail/wiki/Manual Shows how to add custom headers to an email. This can be used for non-standard email fields or specific client requirements. ```java Email email = new Email(); email.addHeader("X-Priority", 2); ``` -------------------------------- ### Maven Settings.xml GPG Profile Source: https://github.com/bbottema/simple-java-mail/blob/master/how to release.txt Define a Maven profile to specify the GPG executable and passphrase. This allows for automated GPG signing during the build process. ```xml gpg gpg password gpg ``` -------------------------------- ### Apply Custom Properties to Mailer Session Source: https://github.com/bbottema/simple-java-mail/wiki/Manual Demonstrates how to apply custom JavaMail properties to the Mailer's internal Session instance. This allows for fine-tuning connection and timeout settings. ```java Properties props = new Properties(); props.setProperty("mail.smtp.timeout", 30 * 1000); props.setProperty("mail.smtp.connectiontimeout", 10 * 1000); Mailer mailer = new Mailer("smtp.host.com", 25, "username", "password"); mailer.applyProperties(props); ```