如何使用Java使SMTP服务器安全

时间:2013-09-21 11:43:34

标签: java security spring-security smtp

我正在使用Spring框架在Java中构建一个银行应用程序,该框架涉及发送电子邮件(使用SMTP服务器),但我听说它不安全。那么如何在Java中使SMTP安全? SSL层和/或HTTPS连接是否足够?请帮忙。

感谢。

2 个答案:

答案 0 :(得分:0)

您需要对SMTP服务器进行配置更改,以便服务器仅从特定ID中继邮件而忽略其他邮件,而不是在您的Java应用程序中使SMTP安全。

答案 1 :(得分:0)

显然,您可以在Spring上使用SMTP over SSL。这是样本:

XML资源

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailS enderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="465" />
<property name="protocol" value="smtps" />
<property name="username" value="yourAccount@gmail.com"/>
<property name="password" value="yourPassword"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtps.auth">true</prop>
<prop key="mail.smtps.starttls.enable">true</prop>
<prop key="mail.smtps.debug">true</prop>
</props>
</property>
</bean>

<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage" >
<property name="from" value="yourAccount@gmail.com" />
<property name="subject" value="Your Subject" />
</bean>

</beans>

测试类

package test.mail;

import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.test.AbstractDependencyInjecti onSpringContextTests;

/**
* MailTest.
* @author jalarcon
*/
public class MailTest extends AbstractDependencyInjectionSpringContextTests {

private MailSender mailSender;
private SimpleMailMessage mailMessage; 

/* (non-Javadoc)
* @see org.springframework.test.AbstractSingleSpringConte xtTests#getConfigLocations()
*/
@Override
protected String[] getConfigLocations() {
return new String[] {"/beanDictionary/mail.xml"};
}

public void testSendMail() {
//Create a thread safe "sandbox" of the message
SimpleMailMessage msg = new SimpleMailMessage(this.mailMessage);
msg.setTo("yourAccount@gmail.com");
msg.setText("This is a test");
try{
mailSender.send(msg);
} catch(MailException ex) {
throw new RuntimeException(ex);
} 
}

// ---------------------------------------------------------- getters/setters

/**
* @return the mailSender
*/
public MailSender getMailSender() {
return mailSender;
}

/**
* @param mailSender the mailSender to set
*/
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}

/**
* @return the mailMessage
*/
public SimpleMailMessage getMailMessage() {
return mailMessage;
}

/**
* @param mailMessage the mailMessage to set
*/
public void setMailMessage(SimpleMailMessage mailMessage) {
this.mailMessage = mailMessage;
}

}