Answer the question
In order to leave comments, you need to log in
Why timeout when sending office365 emails over smtp in java?
I have an Office 365 account. I tried to send mail using java programs that I could find on the Internet (via smtp.office365.com). Always get a timeout exception.
Do you have source code examples that definitely work?
Example
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SendEmailOffice365 {
private static final Logger LOGGER = Logger.getAnonymousLogger();
private static final String SERVER_HOST = "smtp.office365.com";
private static final int SERVER_PORT = 587;
private static final String LOGIN = "========";
private static final String PASSWORD = "========";
private static final String from = "========";
private static final String to = "========";
private static final String subject = "Test";
private static final String messageContent = "Test message";
private static void sendEmail() {
final Session session = Session.getInstance(getEmailProperties(), new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(LOGIN, PASSWORD);
}
});
try {
final Message message = new MimeMessage(session);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress(from));
message.setSubject(subject);
message.setText(messageContent);
message.setSentDate(new Date());
Transport.send(message);
} catch (final MessagingException ex) {
LOGGER.log(Level.WARNING, "Error sending message: " + ex.getMessage(), ex);
}
}
private static Properties getEmailProperties() {
final Properties config = new Properties();
config.put("mail.smtp.auth", "true");
config.put("mail.smtp.starttls.enable", "true");
config.put("mail.transport.protocol", "smtp");
config.put("mail.smtp.host", SERVER_HOST);
config.put("mail.smtp.port", SERVER_PORT);
config.put("mail.smtp.user", LOGIN);
config.put("mail.smtp.password", PASSWORD);
config.put("mail.smtp.connectiontimeout", "2000");
config.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
return config;
}
public static void main(final String[] args) {
sendEmail();
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question