java 發送郵件,可以選擇spring接口或javamail,網上關于這兩種方式的代碼有很多。
如果需要發送html格式的郵件,使用模版會比較友善。
BodyPart html = new MimeBodyPart();
html.setContent(content, "text/html; charset=UTF-8");
其中content利用VelocityEngineUtils的mergeTemplateIntoString方法渲染。
String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mailTemplate.vm", "GBK", map);
注意velocityEngine一定要這樣配置,否則會亂碼。亂的一塌糊塗~~~~
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<props>
<prop key="input.encoding">GBK</prop>
<prop key="output.encoding">GBK</prop>
<prop key="default.contentType">text/html; charset=GBK</prop>
</props>
</property>
</bean>
原因:(Eclipse下)右鍵點選你的mailTemplate.vm模版檔案,選擇屬性Properties,發現

Eclipse中的Text File Encoding代表檢視檔案時的編碼,也就是說檔案本來的編碼是GBK,是以你用GBK檢視才不會亂碼。如果本來是GBK的編碼,在Eclipse中用UTF-8去檢視,肯定顯示亂碼。
so,velocityEngine渲染時,同理,也需用GBK,否則無法解析你的vm或jsp模版檔案。
而vm頁面中的charset是搜尋引擎用來解析的,跟渲染無關。