Tuesday, February 3, 2009

Spring Mail and Gmail SMTP server

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:

<!-- Mail Sender -->
<bean
id= "mailSender" class= "org.springframework.mail.javamail.JavaMailSenderImpl" >
  <property
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" >
    <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>

We could take to a property file the relevant properties:

mail.
host = smtp. googlemail . com
mail.
port = 465
mail.
username = yourUsername
mail.
password = yourPassword
mail.
protocol = smtps

Let’s see an integrational test for this:

public class SimpleMailSenderTest extends AbstractDependencyInjectionSpringContextTests {
  
protected MailSender mailSender ;
  
public SimpleMailSenderTest () {
    setPopulateProtectedVariables
( true );
  
}
  @
Override
  
protected String [] getConfigLocations () {
    
return new String [] { ”applicationContext. xml };
  
}
  
public void testSendEmail () throws Exception {
    SimpleMailMessage simpleMessage =
new SimpleMailMessage ();
    simpleMessage.
setFrom ( ”fromEmail” );
    simpleMessage.
setTo ( ”toEmail” );
    simpleMessage.
setText ( ”Testing text” );
    simpleMessage.
setSubject ( ”Testing subject” );
    mailSender.
send ( simpleMessage );
  
}
}

In case we have a template for sending these emails we could define a template message bean:

<bean
id= "templateMessage" class= "org.springframework.mail.SimpleMailMessage" >
  <property
name= "from" value= "fromAddress" />
  <property
name= "to" value= "toAddress" />
</bean>

Alternatively, we could also specify replyTo, cc, bcc, sentDate, subject and text.



No comments: