我正在关注This link发送电子邮件(Gmail smtp) 我的问题是为什么我要在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="from@no-spam.com" />
<property name="to" value="to@no-spam.com" />
<property name="subject" value="Testing Subject" />
<property name="text">
<value>
<![CDATA[
Dear %s,
Mail Content : %s
]]>
</value>
</property>
</bean>
答案 0 :(得分:7)
如果您使用gmail帐户进行测试,则需要在此处启用Access for less secure app选项: https://www.google.com/settings/security/lesssecureapps
否则您可能会收到身份验证错误。
答案 1 :(得分:5)
您可以通过将电子邮件属性放在外部属性文件中来避免对电子邮件属性进行硬编码,例如email.properties
。如果在配置文件中启用context
命名空间,Spring将加载属性文件,并允许通过表达式语言使用文件中的属性。
<强> Email.properties 强>
email.host=smtp.gmail.com
email.port=587
email.username=username
email.password=password
配置文件
<!-- 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>