Spring Mail and Gmail SMTP server
February 1, 2008 at 9:04 pm · Filed under open source, spring
In case you need to use Spring Mail with Gmail SMTP server, first of all configure a mail sender bean:
id= "mailSender" class= "org.springframework.mail.javamail.JavaMailSenderImpl"
<!-- Mail Sender -->
<bean>
name= "host" value= "${mail.host}"
<property/>
name= "port" value= "${mail.port}"
<property/>
name= "username" value= "${mail.username}"
<property/>
name= "password" value= "${mail.password}"
<property/>
name= "protocol" value= "${mail.protocol}"
<property/>
name= "javaMailProperties"
<property>
key= "mail.smtps.auth"
<props>
<prop>true</prop>
key= "mail.smtps.starttls.enable"
<prop>true</prop>
key= "mail.smtps.debug"
<prop>true</prop>
</props>
</property>
</bean>
We could take to a property file the relevant properties:
host =
mail.smtp.
googlemail .
com
port = 465
mail.
username = yourUsername
mail.
password = yourPassword
mail.
protocol =
mail.smtps
Let’s see an integrational test for this:
public class SimpleMailSenderTest
extends AbstractDependencyInjectionSpringContextTests
{
protected
MailSender mailSender
;
public
SimpleMailSenderTest
() {
( true );
setPopulateProtectedVariables
}
Override
@
protected String []
getConfigLocations
() {
return new String [] {
”applicationContext.
xml ”
};
}
public void
testSendEmail
() throws Exception {
new
SimpleMailMessage simpleMessage =SimpleMailMessage
();
setFrom (
simpleMessage.”fromEmail”
);
setTo (
simpleMessage.”toEmail”
);
setText (
simpleMessage.”Testing text”
);
setSubject (
simpleMessage.”Testing subject”
);
send (
mailSender.simpleMessage
);
}
}
In case we have a template for sending these emails we could define a template message bean:
id= "templateMessage" class= "org.springframework.mail.SimpleMailMessage"
<bean>
name= "from" value= "fromAddress"
<property/>
name= "to" value= "toAddress"
<property/>
</bean>
Alternatively, we could also specify replyTo, cc, bcc, sentDate, subject and text.
No comments:
Post a Comment