开发者

How to configure Spring JavaMailSenderImpl for Gmail

开发者 https://www.devze.com 2022-12-15 20:24 出处:网络
I am trying to find the correct properties to use to connect to the Gmail SMTP sever using the JavaMailSenderImpl class.

I am trying to find the correct properties to use to connect to the Gmail SMTP sever using the JavaMailSenderImpl class.

Let me first say that I have tried the approach found here. This worked fine. But when I tried the configurat开发者_Go百科ion below that post with the exact same authentication information I received a javax.mail.AuthenticationFailedException.

My currently configuration looks like this.

<bean id="mailSender" class ="org.springframework.mail.javamail.JavaMailSenderImpl" >
    <property name="username" value="XXX@gmail.com" />
    <property name="password" value="XXX" />
    <property name="javaMailProperties">
    <props>
        <prop key="mail.smtp.host">smtp.gmail.com</prop>
        <prop key="mail.smtp.port">587</prop>
        <prop key="mail.smtp.auth">true</prop>
        <prop key="mail.smtp.starttls.enable">true</prop>
    </props>
    </property>
</bean>

Why am I still getting this javax.mail.AuthenticationFailedException if I know that my credentials are correct.

Update

Here is my updated code based on the answers below. I am still receiving the same exception.

<bean id="mailSender" class ="org.springframework.mail.javamail.JavaMailSenderImpl" >
    <property name="username" value="XXX@gmail.com" />
    <property name="password" value="XXX" />
    <property name="javaMailProperties">
    <props>
        <prop key="mail.smtp.from">XXX@gmail.com</prop>
        <prop key="mail.smtp.user">XXX@gmail.com</prop>
        <prop key="mail.smtp.password">XXX</prop>
        <prop key="mail.smtp.host">smtp.gmail.com</prop>
        <prop key="mail.smtp.port">587</prop>
        <prop key="mail.smtp.auth">true</prop>
        <prop key="mail.smtp.starttls.enable">true</prop>
    </props>
    </property>
</bean>


This worked for me:

        <property name="host"><value>smtp.gmail.com</value></property>
        <property name="port"><value>587</value></property>
        <property name="protocol"><value>smtp</value></property>
        <property name="username"><value>${mail.username}</value></property>
        <property name="password"><value>${mail.password}</value></property>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.smtp.quitwait">false</prop>
            </props>
        </property>

The real trick for me turned out to be that the "protocol" value has to be "smtp" (not "smtps").


I struggled for an hour to find the right settings to send an email from Gmail using javamailsender and finally did it. I'm posting this as I cannot find a comprehensive example to send through gmail with javamailsender so hopefully this will help someone who want to do the same thing:

STEP 1:

Add the following settings to mail.properties:

mail.protocol=smtp
mail.host=smtp.gmail.com
mail.port=465
mail.smtp.socketFactory.port=465
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.debug=true
mail.smtp.starttls.required=true
mail.smtp.socketFactory.fallback=false
mail.from=XXX@gmail.com
mail.username=XXX@gmail.com
mail.password=my_password

And then in your mailConfiguration class, @Value them in:

@Configuration
@PropertySource("classpath:mail.properties")
public class MailConfiguration {

    @Value("${mail.protocol}")
    private String protocol;
    @Value("${mail.host}")
    private String host;
    @Value("${mail.port}")
    private int port;
    @Value("${mail.smtp.socketFactory.port}")
    private int socketPort;
    @Value("${mail.smtp.auth}")
    private boolean auth;
    @Value("${mail.smtp.starttls.enable}")
    private boolean starttls;
    @Value("${mail.smtp.starttls.required}")
    private boolean startlls_required;
    @Value("${mail.smtp.debug}")
    private boolean debug;
    @Value("${mail.smtp.socketFactory.fallback}")
    private boolean fallback;
    @Value("${mail.from}")
    private String from;
    @Value("${mail.username}")
    private String username;
    @Value("${mail.password}")
    private String password;

    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

        Properties mailProperties = new Properties();
        mailProperties.put("mail.smtp.auth", auth);
        mailProperties.put("mail.smtp.starttls.enable", starttls);
        mailProperties.put("mail.smtp.starttls.required", startlls_required);
        mailProperties.put("mail.smtp.socketFactory.port", socketPort);
        mailProperties.put("mail.smtp.debug", debug);
        mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        mailProperties.put("mail.smtp.socketFactory.fallback", fallback);

        mailSender.setJavaMailProperties(mailProperties);
        mailSender.setHost(host);
        mailSender.setPort(port);
        mailSender.setProtocol(protocol);
        mailSender.setUsername(username);
        mailSender.setPassword(password);
        return mailSender;
    }
}

Please note that my Spring server is SSL enabled so that is why I'm using port 465. For SSL use port 465. If you are using 487, you must be using TLS.

STEP 2:

Following this link and choose to turn on access to less secure apps.

https://www.google.com/settings/security/lesssecureapps

STEP 3:

Turn off AVAST if you have it on your PC. The AVAST Mail Shield conflicts with sending out emails. If you do not turn it off, you will get the following error:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Exception reading response; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target.


For Gmail to work with TLS or SSL:

Port for TLS/STARTTLS: 587
Port for SSL: 465

Both are manditory paramater are javax.net.ssl.SSLSocketFactory, mail.smtp.socketFactory.fallback and make mail.smtp.starttls.enable to false.

<beans>
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host"><value>smtp.gmail.com</value></property>
        <property name="port"><value>465</value></property>
        <property name="protocol"><value>smtp</value></property>
        <property name="username"><value>XXXXX@gmail.com</value></property>
        <property name="password"><value>XXXX</value></property>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">false</prop>
                <prop key="mail.smtp.quitwait">false</prop>
                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
                <prop key="mail.smtp.socketFactory.fallback">false</prop>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>
    <bean id="mailMail" class="com.embitel.service.email.EmailService">
        <property name="mailSender" ref="mailSender" />
        <property name="simpleMailMessage" ref="customeMailMessage" />
    </bean>
    <bean id="customeMailMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="from" value="XXXX@gmail.com" />
        <property name="to" value="yyyyy@gmail.com" />
        <property name="subject" value="Testing Subject Line for email senind.." />
        <property name="text">
            <value>
        <![CDATA[
            Dear %s,
            Mail Content : %s
        ]]>
            </value>
        </property>
    </bean>
</beans>

worked like a charm!!!


The config below (yaml format) worked for me after

  • I disabled 2 factor authentication https://support.google.com/accounts/answer/1064203?hl=en&ref_topic=7189195
  • I enabled less secure apps https://www.google.com/settings/security/lesssecureapps

spring.mail:
  host: smtp.gmail.com
  port: 465
  protocol: smtp
  username: xyz@gmail.com
  password: abc
  test-connection: true
  properties:
    "mail.smtp.auth": true
    "mail.smtp.starttls.enable": true
    "mail.smtp.starttls.required": true
    "mail.smtp.socketFactory.class": javax.net.ssl.SSLSocketFactory
    "mail.debug": true


The only property needed for GMail is

<prop key="mail.smtp.starttls.enable">true</prop>


Sometime/first time google prevent the sign in to your account by any third party application or using your code. when you will sign in to your account in browser, you will get a message "Google prevents a Suspicious attempt to sign in to your account" see the screenshot below.

How to configure Spring JavaMailSenderImpl for Gmail

click on the "Was it you" and allow the sign in.


Here's the javaConfig that worked for me:

    public JavaMailSender getJavaMailSender()
    {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setProtocol("smtp");
        sender.setHost("smtp.gmail.com");
        sender.setPort(587);
        sender.setUsername("username");
        sender.setPassword("password");

        Properties mailProps = new Properties();
        mailProps.put("mail.smtps.auth", "true");
        mailProps.put("mail.smtp.starttls.enable", "true");
        mailProps.put("mail.smtp.debug", "true");

        sender.setJavaMailProperties(mailProps);

        return sender;
    }

I think you need to use port 587 for the TLS to work.


This worked for me:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="465" />
    <property name="protocol" value="smtps" />
    <property name="username" value="my_email@domain.tld" />
    <property name="password" value="my_password" />
    <property name="javaMailProperties">
    <props>
        <prop key="mail.smtps.auth">true</prop>
    </props>
    </property>
</bean>

See Google support for further information: http://support.google.com/mail/bin/answer.py?hl=en&answer=78799


I was also facing this authentication exception and this is because of the gmail security. Open the following url

https://www.google.com/settings/security/lesssecureapps

and enable the less security feature.


This doesn't seem significantly different, but perhaps try:

<bean id="mailSender" class ="org.springframework.mail.javamail.JavaMailSenderImpl" >
    <property name="username" value="XXX@gmail.com" />
    <property name="password" value="XXX" />
    <property name="javaMailProperties">
    <props>
        <prop key="mail.smtp.user" value="XXX@gmail.com" />
        <prop key="mail.smtp.password" value="XXX" />
        <prop key="mail.smtp.host">smtp.gmail.com</prop>
        <prop key="mail.smtp.port">587</prop>
        <prop key="mail.smtp.auth">true</prop>
        <prop key="mail.smtp.starttls.enable">true</prop>
    </props>
    </property>
</bean>


You should specify your "from" address, either as <prop key="mail.smtp.from">XXX@gmail.com</prop>, or when creating a message.


I have resoloved your question.

how to implements an async email service in spring

Note, this works on spring 3 , so I am not sure with spring 2.

0

精彩评论

暂无评论...
验证码 换一张
取 消