M
M
MaxLich2020-02-10 11:37:54
Java
MaxLich, 2020-02-10 11:37:54

How to send emails using a certificate to authenticate against an SMTP server?

I need to send emails from the backend. I have all the data: certificate, login, password, ports, server address, etc. I can't figure out/find how to attach a certificate to authentication on the SMTP-server. For example, this is how I get the certificate from the repository:

final Certificate certificate;
try {
    certificate = keyStoreService.loadCertificate(settings.getCertificateAlias());
} catch (KeyStoreServiceException e) {
    final String errMsg = "An error occurred during work with Java KeyStore: " + e.toString();
    logger.error(errMsg, e);
    throw new RuntimeException(errMsg, e);
}


But I did not find where to attach it to javax.mail.Sessionor to some other object that is used to send letters.

For example, my code for opening a session is:
public Session openSession() {
    logger.trace("SSL Start");

    Properties props = new Properties();
    AppSettings settings = dbService.getAppSettings();
    props.put("mail.smtp.host", settings.getMailServer()); //SMTP Host

    final Certificate certificate;
    try {
        certificate = keyStoreService.loadCertificate(settings.getCertificateAlias());
    } catch (KeyStoreServiceException e) {
        final String errMsg = "An error occurred during work with Java KeyStore: " + e.toString();
        logger.error(errMsg, e);
        throw new RuntimeException(errMsg, e);
    }

    props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
    props.put("mail.smtp.port", settings.getMailServerPort()); //SMTP Port

    props.put("mail.debug", settings.getMailDebug());


    //create Authenticator object to pass in Session.getInstance argument
    Authenticator auth = new Authenticator() {
        //override the getPasswordAuthentication method
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(settings.getMailLogin(), settings.getMailPassword());
        }
    };
    return Session.getInstance(props, auth);
}

This is how the email is sent:
public static void sendEmail(Session session, String toEmail, String subject, String body, String fromAlias, String fromEmail) {
    try {
        MimeMessage msg = new MimeMessage(session);
        //set message headers
        msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
        msg.addHeader("format", "flowed");
        msg.addHeader("Content-Transfer-Encoding", "8bit");
        msg.setFrom(new InternetAddress(fromEmail, fromAlias));
        msg.setReplyTo(InternetAddress.parse(fromEmail, false));
        msg.setSubject(subject, "UTF-8");
        if (body == null)
            body = "";
        msg.setText(body, "UTF-8");
        msg.setSentDate(new Date());
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

        logger.info("Message is ready");
        Transport.send(msg);
        logger.info("EMail has been sent successfully!!");
    } catch (Exception e) {
        final String errMsg = String.format("An error occurred while sending an email with subject = '%s' and body = '%s', recipient = '%s': %s",
                subject, body, toEmail, e.toString());
        logger.error(errMsg, e);
    }
}


Our system administrator tried to send mail via postfix from there, and everything worked there. He used the following postfix settings:
relayhost = хх.хх.хх.хх:25
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = may
smtp_generic_maps = hash:/etc/postfix/generic
smtp_tls_cert_file  = /etc/postfix/cert.pem
local_header_rewrite_clients = static:all

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Demchenko, 2020-02-18
@DaniilDemchenko

I'm sorry, but did you copy the error from the Java KeyStore from the logs?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question