1、添加依賴包java
.....spring
compile "org.springframework:spring-context-support:4.0.1.RELEASE"測試
compile "javamail:javamail:1.3.2"ui
compile "jaf:activation:1.0.2"this
2、先上bean的配置(beans.xml)spa
<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>
3、簡單的發送郵件code
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; } }
4、發送帶附件的郵件xml
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; } }
5、測試圖片
@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(); }
6、發送成功ip
七、總結
看實例,簡單易懂,可根據本身需求隨意改動。