Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Send email from Gmail

Tags:

java

email

spring

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>
like image 632
Sara Avatar asked Aug 09 '26 22:08

Sara


2 Answers

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.

like image 94
cn123h Avatar answered Aug 11 '26 11:08

cn123h


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>
like image 40
Kevin Bowersox Avatar answered Aug 11 '26 12:08

Kevin Bowersox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!