Sara
Sara

Reputation: 2436

Spring: Send email from Gmail

I am following This link for sending email (Gmail smtp) My problem is that why should I hardcode sender and receiver in the bean?

<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="username" />
   <property name="password" value="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="mailMail" class="com.mkyong.common.MailMail">
        <property name="mailSender" ref="mailSender" />
        <property name="simpleMailMessage" ref="customeMailMessage" />
  </bean>

  <bean id="customeMailMessage"
class="org.springframework.mail.SimpleMailMessage">

       <property name="from" value="[email protected]" />
       <property name="to" value="[email protected]" />
       <property name="subject" value="Testing Subject" />
       <property name="text">
       <value>
        <![CDATA[
        Dear %s,
        Mail Content : %s
          ]]>
        </value>
           </property>
   </bean>

Upvotes: 1

Views: 5144

Answers (2)

cn123h
cn123h

Reputation: 2332

if you test with gmail account, you need to enable the Access for less secure app option here: https://www.google.com/settings/security/lesssecureapps

otherwise you may get an authentication error.

Upvotes: 7

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

You can avoid hard coding the email properties by placing the email properties in an external properties file, say email.properties. If you enable the context namespace within your configuration file Spring will load the properties file and allow properties within the file to be used via the expression language.

Email.properties

email.host=smtp.gmail.com
email.port=587
email.username=username
email.password=password

Configuration File

<!-- Spring Loads the Properties File, which can be used for resolution of EL Expressions -->
<context:property-placeholder location="classpath:META-INF/db/db.properties"/>

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
   <property name="host" value="${email.host}" />
   <property name="port" value="${email.port}" />
   <property name="username" value="${email.username}" />
   <property name="password" value="${email.password}" />

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

Upvotes: 5

Related Questions