Spring 內置了一個郵件發送器 JavaMailSenderImpl,能夠用它來發送文本郵件、HTML 郵件而且發送附件。html
具體詳細的功能和簡介這裏就很少說了,直接帶你們作一遍:java
一段可運行的代碼比說不少廢話強得多spring
S1 :首先要保證項目當中使用 SPRING 服務器
Spring官網: http://projects.spring.io/spring-framework/
session
S2:配置郵件參數文件 jdbc.properties(你懂的...偷個懶)app
#配置服務器郵件帳號信息 #服務器 mail.smtp.host=smtp.xxx.com #是否須要驗證密碼 mail.smtp.auth=true #超時時間 mail.smtp.timeout=25000 #發件人信箱 mail.smtp.from=xxx@163.com #用戶名 mail.smtp.username=xxx@163.com #密碼 mail.smtp.password=123456
S3:配置 applicationContext.xmljsp
首先配置配置文件路徑,這裏配置的是 jdbc.properties,而後配置 JavaMailSenderImpl,參數從 jdbc.properties 當中得到測試
<!-- in-memory database and a datasource --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="classpath:jdbc.properties" />
<!-- 配置郵件 senderbean --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="${mail.smtp.host}"></property> <property name="javaMailProperties" > <props> <prop key="mail.smtp.auth">${mail.smtp.auth}</prop> <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop> </props> </property> <property name="username" value="${mail.smtp.username}"></property> <property name="password" value="${mail.smtp.password}"></property> </bean>
S4:編寫 ACTION 代碼,實現郵件發送功能,這裏還附加了一個附件,若是文件是從前臺傳遞過來的能夠用的上 ACTION 當中的參數,這裏只是作了一個模擬。將上述代碼拷貝到項目當中便可運行。this
/** ******************************************************************************************** * @ClassName: ForcastAction * @Description: TODO * @author ZhouQian * @date 2014-6-11-上午11:00:34 ******************************************************************************************** */ public class ForcastAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware { private static final long serialVersionUID = 1L; private HttpServletRequest request; private HttpServletResponse response; // struts mapsession ,key value private Map<String, Object> session; // 郵件發送器 private JavaMailSenderImpl mailSender; // 設定上傳文件路徑 private static final String FOLDER_NAME = "/upload/"; // 上傳的附件和附件名稱 private File[] attachment; private String[] attachmentFileName; /** * 郵件發送 接口用於向測試用戶發送郵件 後期可能採用定時器進行郵件發送 */ public void sendEmail() { // 郵件POJO 對象 MailPojo mailPojo = new MailPojo(); MimeMessage m = mailSender.createMimeMessage(); // 構造附件 String path = "jsp/theme/analyser/hero.html"; path = request.getSession().getServletContext().getRealPath("/") + path; attachment = new File[1]; attachment[0] = new File(path); attachmentFileName = new String[1]; attachmentFileName[0] = "hero.html"; try { MimeMessageHelper helper = new MimeMessageHelper(m, true, "UTF-8"); // 設置收件人 helper.setTo("xxx@163.com"); // 設置抄送 // helper.setCc(""); // 設置發件人 helper.setFrom("xxx@163.com"); // 設置暗送 // helper.setBcc(""); // 設置主題 helper.setSubject("測試郵件!"); // 設置 HTML 內容 helper.setText("這只是一封測試郵件!若是你收到的話說明我已經發送成功了!"); // 保存附件,這裏作一個 copy 只是爲了防止上傳文件丟失 attachment = saveFiles(attachment, attachmentFileName); for (int i = 0; attachment != null && i < attachment.length; i++) { File file = attachment[i]; // 附件源 FileSystemResource resource = new FileSystemResource(file); helper.addAttachment(attachmentFileName[i], resource); // mail 對象填充 AttachmentPojo attachmentPojo = new AttachmentPojo(); attachmentPojo.setFilename(attachmentFileName[i]); attachmentPojo.setFilepath(file.getAbsolutePath()); mailPojo.getAttachmentPojos().add(attachmentPojo); } // 進行郵件發送和郵件持久類的狀態設定z mailSender.send(m); mailPojo.setSent(true); System.out.println("郵件發送成功!"); } catch (Exception e) { e.printStackTrace(); mailPojo.setSent(false); // TODO: handle exception } // dao.create(mail) 進行持久化,若是有這一步的話 } /** * struts 2 會將文件自動上傳到臨時文件夾中,Action運行完畢後臨時文件會被自動刪除 所以須要將文件複製到 /upload 文件夾下 * * @param files * @param names * @return */ public File[] saveFiles(File[] files, String[] names) { if (files == null) return null; File root = new File(ServletActionContext.getServletContext().getRealPath(FOLDER_NAME)); File[] destinies = new File[files.length]; for (int i = 0; i < files.length; i++) { File file = files[i]; File destiny = new File(root, names[i]); destinies[i] = destiny; copyFile(file, destiny); } return destinies; } /** * 複製單個文件 * * @param from * @param to */ public void copyFile(File from, File to) { InputStream ins = null; OutputStream ous = null; try { // 建立全部上級文件夾 to.getParentFile().mkdirs(); ins = new FileInputStream(from); ous = new FileOutputStream(to); byte[] b = new byte[1024]; int len; while ((len = ins.read(b)) != -1) { ous.write(b, 0, len); } } catch (Exception e) { // TODO: handle exception } finally { if (ous != null) try { ous.close(); } catch (Exception e) { e.printStackTrace(); } if (ins != null) try { ins.close(); } catch (Exception e) { e.printStackTrace(); } } } public void setServletResponse(HttpServletResponse httpservletresponse) { this.response = httpservletresponse; } public void setServletRequest(HttpServletRequest httpservletrequest) { this.request = httpservletrequest; } public void setSession(Map<String, Object> session) { this.session = session; } public JavaMailSenderImpl getMailSender() { return mailSender; } public void setMailSender(JavaMailSenderImpl mailSender) { this.mailSender = mailSender; } public File[] getAttachment() { return attachment; } public void setAttachment(File[] attachment) { this.attachment = attachment; } public String[] getAttachmentFileName() { return attachmentFileName; } public void setAttachmentFileName(String[] attachmentFileName) { this.attachmentFileName = attachmentFileName; } }
若是你們有不明白的能夠留言問我,一同進步spa