如何为 Gmail 配置 Spring JavaMailSenderImpl

2022-01-23 00:00:00 gmail spring java

我正在尝试使用 JavaMailSenderImpl 类查找用于连接到 Gmail SMTP 服务器的正确属性.

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

首先让我说我已经尝试过找到的方法 这里.这工作得很好.但是,当我使用完全相同的身份验证信息尝试该帖子下方的配置时,我收到了 javax.mail.AuthenticationFailedException.

Let me first say that I have tried the approach found here. This worked fine. But when I tried the configuration 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>

如果我知道我的凭据正确,为什么我仍然收到此 javax.mail.AuthenticationFailedException.

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

这是我根据以下答案更新的代码.我仍然收到同样的异常.

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>

推荐答案

这对我有用:

        <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>

对我来说真正的诀窍是协议"值必须是smtp"(而不是smtps").

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

相关文章