标签:style http io os ar java sp 2014 art
一、添加依赖包
.....
compile "org.springframework:spring-context-support:4.0.1.RELEASE"
compile "javamail:javamail:1.3.2"
compile "jaf:activation:1.0.2"
二、先上bean的配置(beans.xml)
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <!-- 这里我以163为例 --> <property name="host" value="smtp.163.com"/> <property name="port" value="25"/> <!-- 发送方用户名 --> <property name="username" value="**"/> <!-- 发送方密码 --> <property name="password" value="**"/> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> </props> </property> </bean> <bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage"> <!-- 发送方用户名 --> <property name="from" value="**" /> </bean> <bean id="simpleEmail" class="com.email.example.SimpleMessageDemo"> <property name="mailSender" ref="mailSender"/> <property name="templateMessage" ref="templateMessage"/> </bean> <bean id="attachmentEmail" class="com.email.example.AttachmentsMailDemo"> <property name="sender" ref="mailSender" /> </bean>
三、简单的发送邮件
public class SimpleMessageDemo { private MailSender mailSender; private SimpleMailMessage templateMessage; public void sendMail() { SimpleMailMessage msg = new SimpleMailMessage(templateMessage); msg.setSubject("这是主题"); msg.setTo("**"); // 对方邮箱 msg.setText("内容"); this.mailSender.send(msg); } public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } public void setTemplateMessage(SimpleMailMessage templateMessage) { this.templateMessage = templateMessage; } }
四、发送带附件的邮件
public class AttachmentsMailDemo { private JavaMailSenderImpl sender; // 发送带附件的邮件 public void sendAttachmentEmail() throws AddressException, MessagingException { MimeMessage message = sender.createMimeMessage(); // 第二个参数设置为TRUE,即multipart=true时才能发送附件 MimeMessageHelper helper = new MimeMessageHelper(message, true); // 设置发送方邮箱地址 helper.setFrom(new InternetAddress("**")); // 设置接收方邮箱地址 helper.setTo("**"); // 发送内容 helper.setText("这是内容"); // 附件(假如是个图片) FileSystemResource file = new FileSystemResource(new File( "f:/photo/build.png")); helper.addAttachment("显示的附加名称.jpg", file); // 发送 sender.send(message); } public void setSender(JavaMailSenderImpl sender) { this.sender = sender; } }
五、测试
@Test public void testSendMail() { ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); // 获取bean SimpleMessageDemo smd = (SimpleMessageDemo) ac.getBean("simpleEmail"); // 发送邮件 smd.sendMail(); // 获取bean AttachmentsMailDemo amd = (AttachmentsMailDemo) ac .getBean("attachmentEmail"); // 发送邮件 amd.sendAttachmentEmail(); }
六、发送成功
7、总结
看实例,简单易懂,可根据自己需求随意改动。
标签:style http io os ar java sp 2014 art
原文地址:http://my.oschina.net/u/1177710/blog/323040