java代码:
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class SendMail {
private JavaMailSender sender;
public void sendMessage(String[] to, String from, String subject) throws MessagingException {
MimeMessage msg = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg, true, "GB2312");
helper.setTo(to);
helper.setFrom(from);
helper.setSubject(subject);
helper.setText("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body><h1><a href='#'>郁闷!"
+ "</body></html>", true);
// add the rar file
FileSystemResource rarfile = new FileSystemResource(new File("D:/workspace/netbar-dw/src/netbar/dw/util/SendMail.java"));
helper.addAttachment("SendMail.java", rarfile);
sender.send(msg);
}
public JavaMailSender getSender() {
return sender;
}
public void setSender(JavaMailSender sender) {
this.sender = sender;
}
public static void main(String[] args) throws MessagingException {
ApplicationContext context=new ClassPathXmlApplicationContext("spring-mail.xml");
SendMail send=(SendMail) context.getBean("sendMail");
String [] to={"123@123.com","456@123.com"};
send.sendMessage(to,"123@123.com", "test");
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.123.com">
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
<property name="username" value="123@123.com">
</property>
<property name="password" value="123">
</property>
</bean>
<bean id="sendMail" class="netbar.dw.util.SendMail">
<property name="sender" ref="mailSender"></property>
</bean>
</beans>
SpringMail邮件发送示例
本文介绍了一个使用Spring Mail模块发送包含附件的HTML格式邮件的Java示例。该示例展示了如何配置邮件发送器,设置邮件内容及附件,并通过Spring框架进行依赖注入。
855

被折叠的 条评论
为什么被折叠?



