spring javamail使用

spring提供了java mail插件,很方便发送邮件。
1、spring配置文件增加如下配置
<bean id="mimeMessage" class="javax.mail.internet.MimeMessage" factory-bean="javaMailSender"  
	    factory-method="createMimeMessage" /> 


	<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">   
	    <property name="host" value="邮件服务器地址" />   
	    <property name="username" value="邮箱帐号(不是邮箱名称)" />   
	    <property name="password" value="密码" />   
	    <property name="javaMailProperties">   
	        <props>   
	            <prop key="mail.smtp.auth">true</prop>   
	            <prop key="mail.smtp.timeout">25000</prop>   
	            <!-- <prop key="mail.smtp.port">25</prop>   
	            <prop key="mail.smtp.socketFactory.port">25</prop>   
	            <prop key="mail.smtp.socketFactory.fallback">false</prop>   
	            <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
	            -->   
	        </props>   
	    </property>   
	</bean>  

	<bean id="sendMail" class="com.mindray.protal.common.SendMail">
		<property name="mailSender" ref="javaMailSender" /> 
		<property name="mimeMessage" ref="mimeMessage" /> 
	</bean>  





java代码


public class SendMail {

	private JavaMailSender mailSender;   
	private MimeMessage    mimeMessage; 
	private static Logger logger = Logger.getLogger(SendMail.class);
	
	public JavaMailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}


	public MimeMessage getMimeMessage() {
		return mimeMessage;
	}


	public void setMimeMessage(MimeMessage mimeMessage) {
		this.mimeMessage = mimeMessage;
	}

		  
	  
	/**   
	 * 带附件的HTML格式邮件   
	 * @throws Exception 
	 * @throws MessagingException    
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */   
	public void sendAttachMail(MailBean mail) throws Exception  {   
		String failMail = "";
		try
	    {
			MimeMessageHelper messageHelper = new MimeMessageHelper(this.mimeMessage, true, "UTF-8"); 
			String mailTos[] = mail.getTo().split(";");
			messageHelper.setFrom(mail.getFrom());   
			messageHelper.setSubject(mail.getTitle());   
			messageHelper.setText(mail.getContent(), true);        
			ByteArrayResource ir = new ByteArrayResource(mail.getBytes());
			String filename = MimeUtility.encodeWord(mail.getFilename(),   "UTF-8",   null); 
			messageHelper.addAttachment(filename, ir); 
			for(int i=0; i<mailTos.length ;i++)
			{
				failMail = mailTos[i];
				messageHelper.setTo(mailTos[i]);
				this.mailSender.send(this.mimeMessage);
				logger.info("send mail ok=" + mailTos[i]);
				failMail = "";
			}
	    }
		catch(Exception e)
		{			
		    logger.error(e);
		    if(!"".equals(failMail))
		    {
		    	throw new Exception(e);
		    }
		    else
		    {
		    	throw e;
		    }
		 }
	}
	

}

你可能感兴趣的:(java,spring,html,.net)