TLS issue when sending to gmail through JavaMail

不羁的心 提交于 2019-12-05 04:07:55

You need to enable STARTTLS. Add one more property to your configuration:

props.put("mail.smtp.starttls.enable", "true");
pooja
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class CopyOfSendMail {

private static String SMPT_HOSTNAME = "my smtp port no";
private static String USERNAME = "root";
private static String PASSWORD = "root";

public static void main(String[] args) {
    Properties props = new Properties();
    props.put("mail.smtp.host", SMPT_HOSTNAME);
    props.put("mail.from","aaa@gmail.com");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");

    Session session = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USERNAME, PASSWORD);
        }
    });
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom();
        msg.setRecipients(Message.RecipientType.TO,
                          "bbb@gmail.com");
        msg.setSubject("JavaMail hello world example");
        msg.setSentDate(new Date());
        msg.setText("Hello, world!\n");
        Transport.send(msg);
     } catch (MessagingException mex) {
        System.out.println("send failed, exception: " + mex);
     }
    }
}

Here Mail Sender which is using MSN-SMTP service

My host is smtp.live.com and port is 587.

As given in official doc of Java Mail, here you can get more info about best Java Mail mechanism to send and receive mails.

Properties of Mail Client are:

  Properties mailProps = new Properties();
  mailProps.put("mail.smtp.user",mailID);
  mailProps.put("mail.smtp.host",host);
  mailProps.put("mail.smtp.auth", "true");
  mailProps.put("mail.smtp.port",port);
  mailProps.put("mail.smtp.starttls.enable", "true");
  Session mailSession = Session.getInstance(mailProps,null);

Sending mechanism is :

 SMTPTransport t=(SMTPTransport)mailSession.getTransport("smtp");
 System.out.println(" Taking protocol! ");
 t.connect(host, mailID, password);
 System.out.println(" Connection Successfull! ");
 t.sendMessage(mimMessage,mimMessage.getAllRecipients());

Note:
Code is running well on local Indian Server. But this is not responding at Azur Congo: Both are Linux server.

Error is:

 com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first

Even if system property set manually:

 java -Dmail.smtp.starttls.enable=true SendAMai

also @Rob Harrop and @Brian 's points are ensured

if you're on Linux ensure that you have libnss3 and openssl installed
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!