JavaEE : "Access to default session denied" when sending mail using smtp.gmail.com

Posted by Harry Pham on Stack Overflow See other posts from Stack Overflow or by Harry Pham
Published on 2010-12-28T05:48:37Z Indexed on 2010/12/28 5:53 UTC
Read the original article Hit count: 359

Filed under:
|
|
|

I am trying to write email authentication feature for my website and I encounter some issues. I got java.lang.SecurityException: Access to default session denied, when I try to do Session.getDefaultInstance. Here are my codes:

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailSubjectTxt = "Email Confirmation";
    private static final String emailFromAddress = "[email protected]";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";    
    ...
    String sendTo = "[email protected]";
    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");
    //It dies at the next line
    Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
        @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("myUserName", "myPassword");
            }
        });

    session.setDebug(debug);
    //Set the FROM address
    Message msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress(emailFromAddress);
    msg.setFrom(addressFrom);
    //Set the TO address
    InternetAddress[] addressTo = new InternetAddress[1];
    addressTo[0] = new InternetAddress(sendTo);
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    //Construct the content of the email confirmation
    String message = "Test Content"
    // Setting the Subject and Content Type
    msg.setSubject(emailSubjectTxt);
    msg.setContent(message, "text/plain");
    Transport.send(msg);

© Stack Overflow or respective owner

Related posts about java-ee

Related posts about smtp