Languages
[Edit]
EN

Java - send mail with DKIM

4 points
Created by:
leila
255

In this article, we would like to show how to send mail with DKIM in java.

Maven dependency:

<!-- https://mvnrepository.com/artifact/org.simplejavamail/simple-java-mail -->
<dependency>
	<groupId>org.simplejavamail</groupId>
	<artifactId>simple-java-mail</artifactId>
	<version>6.5.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.simplejavamail/dkim-module -->
<dependency>
	<groupId>org.simplejavamail</groupId>
	<artifactId>dkim-module</artifactId>
	<version>6.5.0</version>
</dependency>

Full working example:

package logic;

import org.simplejavamail.api.email.Email;
import org.simplejavamail.api.mailer.config.TransportStrategy;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.MailerBuilder;

import java.io.File;

public class MailSenderWithDkim {

    public static void main(String[] args) {
        String smtpHost = "some-mail-server.com"; // mail server
        int smtpPort = 465;
        String smtpUsername = "username@my-domain.com";
        String smtpPassword = "my-password";

        Email email = EmailBuilder.startingBlank()
                .from("From", "from@gmail.com")
                .to("To", "to@gmail.com")
                //.to("To", "to@gmail.com") // second recipient
                .withSubject("Subject goes here")
                .withPlainText("Our mail body goes here")
                //.withHTMLText("") // if we want HTML instead of plain text
                .signWithDomainKey(
                        // DKIM RSA private key converted to pkcs8_key
                        new File("C:\\projects\\pkcs8_key"),
                        "my-domain-name-goes-here.com", // our domain name
                        "our-dkim-selector-here" // DKIM DNS selector
                )
                .buildEmail();

        MailerBuilder
                .withSMTPServer(smtpHost, smtpPort, smtpUsername, smtpPassword)
                .withTransportStrategy(TransportStrategy.SMTPS)
                .buildMailer()
                .sendMail(email);
    }
}

How to convert RSA private key to pkcs8_key (from PEM to DER)

openssl pkcs8 -topk8 -inform PEM -outform DER -in our-private-key.txt  -nocrypt > pkcs8_key

If we work on windows we can use git bash.

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join