Spring通过Google发送电子邮件()

时间:2011-08-17 13:23:03

标签: java spring gmail

以下代码效果很好

但是,我的问题是如何设置'javaMailProperties'programaticaly? 因为我想从代码中设置ssl / tsl。我无法访问这些属性,我不知道为什么,感谢解决方案和解释。

SimpleMailMessage message=(SimpleMailMessage)SpringUtil.getContext().
getBean("templateMessage");

JavaMailSenderImpl mailSender = (JavaMailSenderImpl)SpringUtil.getContext()
.getBean("mailSender"); 

mailSender.send(message);

--applicationcontext.xml--

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
   <property name="host" value="smtp.gmail.com"/>
   <property name="port" value="587"/>
   <property name="username" value="your gmail address"/>
   <property name="password" value="your password"/>        

   <property name="javaMailProperties">
    <props>
        <prop key="mail.smtp.auth">true</prop>
        <prop key="mail.smtp.starttls.enable">true</prop>
    </props>
</property>

 </bean>

<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage" >
<property name="from" value="from@gmail.com"/>
    <property name="to" value="to@gmail.com"/>              
    <property name="subject" value="subject"/>
    <property name="text" value="hello"/>               
 </bean>

(我不想使用javax.mail方法,有人问过)

2 个答案:

答案 0 :(得分:3)

使用:

mailSender.getJavaMailProperties().setProperty("mail.smtp.starttls.enable", "true");

与要以编程方式设置的其他属性相同。

编辑:

我检查了JavaMailSenderImpl类的源代码:

/**
 * Allow Map access to the JavaMail properties of this sender,
 * with the option to add or override specific entries.
 * <p>Useful for specifying entries directly, for example via
 * "javaMailProperties[mail.smtp.auth]".
 */
public Properties getJavaMailProperties() {
    return this.javaMailProperties;
}

如您所见,getJavaMailProperties是一个公共方法,应该可供您使用。我的Spring框架版本是3.0.5。

答案 1 :(得分:0)

快速谷歌未经验证。 在mailSender.getJavaMailProperties.setProperty上调用setProperty(String key,String value)(“mail.smtp.auth”,true)

http://download.oracle.com/javase/6/docs/api/java/util/Properties.html

相关问题