使用spring框架中的組件發(fā)送郵件功能說明
Spring框架是由于軟件開發(fā)的復(fù)雜性而創(chuàng)建的。Spring使用的是基本的JavaBean來完成以前只可能由EJB完成的事情。然而,Spring的用途不僅僅限于服務(wù)器端的開發(fā)。從簡單性、可測試性和松耦合性角度而言,絕大部分Java應(yīng)用都可以從Spring中受益。
首先進(jìn)入自己的QQ郵箱,在設(shè)置中修改賬戶信息
然后來至底部
點擊開啟,再用手機(jī)發(fā)送對應(yīng)信息到指定號碼,然后點擊我已發(fā)送
獲取授權(quán)碼
注意提示:
到這里,相信你已經(jīng)開通了SMTP服務(wù),這樣就可以在java code發(fā)送郵件了
接下來的是Spring 中使用郵件服務(wù)
首先是配置信息使用的是587端口,剛開始用465端口我糾結(jié)了好久(使用465端口的錯誤詳情),用不了,你可以嘗試,默認(rèn)的25端口應(yīng)該也是不適合的
<!-- 郵件服務(wù) --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.qq.com"/> <property name="port" value="587"/>//或許你可以用465端口,默認(rèn)的25不適合 <property name="protocol" value="smtp"/> <property name="username" value="785427346@qq.com"/> <property name="password" value="xxxxxxxxxxxx"/>//這里的是你通過短信后,獲取的授權(quán)碼 <property name="defaultEncoding" value="UTF-8"/> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.timeout">25000</prop> </props> </property> </bean> <!-- this is a template message that we can pre-load with default state --> <bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="from" value="785427346@qq.com"/> <property name="subject" value="嘗試發(fā)郵件"/> </bean> <bean id="orderManager" class="cn.cherish.common.SimpleOrderManager"> <property name="mailSender" ref="mailSender"/> <property name="templateMessage" ref="templateMessage"/> </bean>
用maven引入的jar包
<!-- 郵件 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
下面只是一個工具類作簡單例子,請勿見怪
package cn.cherish.common; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; /** * 項目名稱:springmvc_hibernate * 類名稱:MailUtil * 類描述: * 創(chuàng)建人:Cherish * 聯(lián)系方式:785427346@qq.com * 創(chuàng)建時間:2016年4月22日 下午3:51:48 * @version 1.0 */ public class MailUtil { private static final String HOST = "smtp.qq.com"; private static final String SMTP = "smtp"; private static final String USERNAME = "785427346@qq.com"; private static final String PASSWORD = "xxxxxxxxxx"; private static final int PORT = 587;//587/465 private static final String DEFAULTENCODING = "UTF-8"; private static JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); private static Properties prop = new Properties(); static{ // 設(shè)定mail server senderImpl.setHost(HOST); senderImpl.setProtocol(SMTP); senderImpl.setUsername(USERNAME); senderImpl.setPassword(PASSWORD); senderImpl.setPort(PORT); senderImpl.setDefaultEncoding(DEFAULTENCODING); // 設(shè)定properties prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.timeout", "25000"); //設(shè)置調(diào)試模式可以在控制臺查看發(fā)送過程 prop.put("mail.debug", "true"); senderImpl.setJavaMailProperties(prop); } public static void main(String args[]) { // 設(shè)置收件人,寄件人 用數(shù)組發(fā)送多個郵件 // String[] array = new String[] {"88888@qq.com","666666@qq.com","999999999@qq.com",USERNAME}; String[] array = new String[] {USERNAME}; String subject = "Cherish內(nèi)嵌圖片、音樂的郵件"; // StringBuffer sb = new StringBuffer(); // try { // URL url = new URL("http://www.imooc.com/");//http://android-studio.org/ // // URLConnection conn = url.openConnection(); // InputStream is = conn.getInputStream(); // // BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // // String string = null; // while ((string = reader.readLine()) != null) { // sb.append(string); // } // // //System.out.println(sb.toString()); // // } catch (Exception e) { // e.printStackTrace(); // } // // boolean result = htmlMail(array, subject, sb.toString()); String filePath = "E:/javaxmail.png"; String html = "<html><head>"+ "</head><body>"+ "<audio src='http://m10.music.126.net/20160422225433/25b43b999bcdaf3425b9194514340596/ymusic/8c94/b9af/69e3/7ebe35b8e00154120822550b21b0c9c5.mp3' autoplay='autoplay' controls='controls' loop='-1'>愛你</audio>"+ "<h1>Hello,Nice to meet you!</h1>"+ "<span style='color:red;font-size:36px;'>并摸了一把你的小奶</span>"+ "<img src='cid:javaxmail.png'>"+ "</body></html>"; boolean result = inlineFileMail(array, subject, html, filePath); if (result) { System.out.println("發(fā)送郵件成功。。。。"); } } /** * 發(fā)送簡單郵件 * @param to 收件人郵箱 * @param subject 主題 * @param content 內(nèi)容 * @return */ public static boolean singleMail(String to, String subject, String content){ String[] array = new String[] {to}; return singleMail(array, subject, content); } /** * 發(fā)送簡單文本郵件 * @param to 收件人郵箱數(shù)組 * @param subject 主題 * @param content 內(nèi)容 * @return */ public static boolean singleMail(String[] to, String subject, String content){ boolean result = true; SimpleMailMessage mailMessage = new SimpleMailMessage(); // 設(shè)置收件人,寄件人 用數(shù)組發(fā)送多個郵件 mailMessage.setTo(to); mailMessage.setFrom(USERNAME); mailMessage.setSubject(subject); mailMessage.setText(content); // 發(fā)送郵件 try { senderImpl.send(mailMessage); } catch (MailException e) { e.printStackTrace(); result = false; } return result; } /** * 發(fā)送html郵件 * @param to 收件人 * @param subject 主題 * @param html html代碼 * @return */ public static boolean htmlMail(String[] to, String subject, String html){ boolean result = true; MimeMessage mailMessage = senderImpl.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage); try { // 設(shè)置收件人,寄件人 用數(shù)組發(fā)送多個郵件 messageHelper.setTo(to); messageHelper.setFrom(USERNAME); messageHelper.setSubject(subject); // true 表示啟動HTML格式的郵件 messageHelper.setText(html, true); // 發(fā)送郵件 senderImpl.send(mailMessage); } catch (MessagingException e) { result = false; e.printStackTrace(); } return result; } /** * 發(fā)送內(nèi)嵌圖片的郵件 (cid:資源名) * @param to 收件人郵箱 * @param subject 主題 * @param html html代碼 * @param imgPath 圖片路徑 * @return */ public static boolean inlineFileMail(String[] to, String subject, String html, String filePath){ boolean result = true; MimeMessage mailMessage = senderImpl.createMimeMessage(); try { //設(shè)置true開啟嵌入圖片的功能 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true); // 設(shè)置收件人,寄件人 用數(shù)組發(fā)送多個郵件 messageHelper.setTo(to); messageHelper.setFrom(USERNAME); messageHelper.setSubject(subject); // true 表示啟動HTML格式的郵件 messageHelper.setText(html, true); FileSystemResource file = new FileSystemResource(new File(filePath)); messageHelper.addInline(file.getFilename(), file); // 發(fā)送郵件 senderImpl.send(mailMessage); } catch (MessagingException e) { result = false; e.printStackTrace(); } return result; } /** * 發(fā)送帶附件的郵件 * @param to * @param subject * @param html * @param filePath * @return */ public static boolean attachedFileMail(String[] to, String subject, String html, String filePath){ boolean result = true; MimeMessage mailMessage = senderImpl.createMimeMessage(); try { // multipart模式 為true時發(fā)送附件 可以設(shè)置html格式 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8"); // 設(shè)置收件人,寄件人 用數(shù)組發(fā)送多個郵件 messageHelper.setTo(to); messageHelper.setFrom(USERNAME); messageHelper.setSubject(subject); // true 表示啟動HTML格式的郵件 messageHelper.setText(html, true); FileSystemResource file = new FileSystemResource(new File(filePath)); // 這里的方法調(diào)用和插入圖片是不同的。 messageHelper.addAttachment(file.getFilename(), file); // 發(fā)送郵件 senderImpl.send(mailMessage); } catch (MessagingException e) { result = false; e.printStackTrace(); } return result; }
溫馨提示:
<img src='cid:javaxmail.png'>
這是內(nèi)嵌圖片的方式 javaxmail.png 要和 messageHelper.addInline(file.getFilename(), file);
這里的 file.getFilename()
相一致就可以
現(xiàn)在只差一步了,那就是Ctrl + F11,有不當(dāng)之處敬請?zhí)岢?,共同進(jìn)步
** 使用javax.mail發(fā)郵件代碼 ** package cn.cherish.utils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage.RecipientType; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * 項目名稱:springmvc_hibernate * 類名稱:EmailUtil * 類描述:發(fā)送郵件工具類 * 創(chuàng)建人:Cherish * 聯(lián)系方式:785427346@qq.com * 創(chuàng)建時間:2016年4月23日 上午9:48:21 * @version 1.0 */ public class EmailUtil { // properties配置文件地址 //private static final String PROPERTIES_PATH = "standard_data.properties"; private static Session session; private static Properties props = new Properties(); private static final String HOST = "smtp.qq.com"; private static int PORT = 587; private static final String isAUTH = "true"; private static final String FROM = "785427346@qq.com"; private static final String USERNAME = "785427346@qq.com"; private static final String PASSWORD = "xxxxxxxxxxxxxxxx"; private static final String TIMEOUT = "25000"; private static final String DEBUG = "true"; // 初始化session static { props.put("mail.smtp.host", HOST); props.put("mail.smtp.port", PORT); props.put("mail.smtp.auth", isAUTH); props.put("fromer", FROM); props.put("username", USERNAME); props.put("password", PASSWORD); props.put("mail.smtp.timeout", TIMEOUT); props.put("mail.debug", DEBUG); session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(USERNAME, PASSWORD); } }); } public static void main(String[] args) { try { String html = "<html><head>"+ "</head><body>"+ "<audio src='http://219.128.78.22/m10.music.126.net/20160423105749/3cee5688a7dc87d28a265fd992ecb0a2/ymusic/8c94/b9af/69e3/7ebe35b8e00154120822550b21b0c9c5.mp3?wshc_tag=1&wsts_tag=571aded1&wsid_tag=b73f773e&wsiphost=ipdbm' autoplay='autoplay' controls='controls' loop='-1'>愛你</audio>"+ "<video controls='controls'>"+ "<source src='http://v2.mukewang.com/45ad4643-87d7-444b-a3b9-fbf32de63811/H.mp4?auth_key=1461379796-0-0-e86cefa71cef963875fd68f8a419dd8a' type='video/mp4' />"+ "Your browser does not support the video tag."+ "</video>"+ "<h1>Hello,nice to fuck you!</h1>"+ "<span style='color:red;font-size:36px;'>并抓了一把你的小雞雞</span>"+ "</body></html>"; //sendEmail("785427346@qq.com", "yeah", html, true); sendFileEmail("785427346@qq.com", "yeah", html, new File("E:/xiaoming.zip")); } catch (Exception e) { e.printStackTrace(); } } /** * * @Title sendEmail * @Description 通過isHtml判斷發(fā)送的郵件的內(nèi)容 * @param to 郵件接收者 * @param content 郵件內(nèi)容 * @param isHtml 是否發(fā)送html * @throws MessagingException * @throws IOException * @throws FileNotFoundException * @throws EmailException */ public static void sendEmail(String to, String title, String content, boolean isHtml) throws FileNotFoundException, IOException, MessagingException { String fromer = props.getProperty("fromer"); if (isHtml) { sendHtmlEmail(fromer, to, title, content); } else { sendTextEmail(fromer, to, title, content); } } // 發(fā)送純文字郵件 public static void sendTextEmail(String from, String to, String subject, String content) throws FileNotFoundException, IOException, MessagingException { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(content); message.setSentDate(new Date()); Transport.send(message); } // 發(fā)送有HTML格式郵件 public static void sendHtmlEmail(String from, String to, String subject, String htmlConent) throws FileNotFoundException, IOException, MessagingException { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); Multipart multi = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(htmlConent, "text/html; charset=utf-8"); multi.addBodyPart(html); message.setContent(multi); Transport.send(message); } // 發(fā)送帶附件的郵件 public static void sendFileEmail(String to, String subject, String htmlConent, File attachment) throws FileNotFoundException, IOException, MessagingException { Message message = new MimeMessage(session); String fromer = props.getProperty("fromer"); message.setFrom(new InternetAddress(fromer)); message.setRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); // 向multipart對象中添加郵件的各個部分內(nèi)容,包括文本內(nèi)容和附件 Multipart multipart = new MimeMultipart(); // 添加郵件正文 BodyPart contentPart = new MimeBodyPart(); contentPart.setContent(htmlConent, "text/html;charset=UTF-8"); multipart.addBodyPart(contentPart); // 添加附件的內(nèi)容 if (attachment != null) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); attachmentBodyPart.setDataHandler(new DataHandler(source)); // 網(wǎng)上流傳的解決文件名亂碼的方法,其實用MimeUtility.encodeWord就可以很方便的搞定 // 這里很重要,通過下面的Base64編碼的轉(zhuǎn)換可以保證你的中文附件標(biāo)題名在發(fā)送時不會變成亂碼 // sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); // messageBodyPart.setFileName("=?GBK?B?" + // enc.encode(attachment.getName().getBytes()) + "?="); // MimeUtility.encodeWord可以避免文件名亂碼 attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName())); multipart.addBodyPart(attachmentBodyPart); } message.setContent(multipart); Transport.send(message); } }
總結(jié)
以上所述是小編給大家介紹的使用spring框架中的組件發(fā)送郵件,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- Spring Boot發(fā)送郵件詳解
- Spring Boot 發(fā)送郵件功能案例分析
- springMVC發(fā)送郵件的簡單實現(xiàn)
- Spring+quartz實現(xiàn)定時發(fā)送郵件功能實例
- Spring Boot實戰(zhàn)之發(fā)送郵件示例代碼
- Java使用Spring發(fā)送郵件的實現(xiàn)代碼
- Spring Boot中利用JavaMailSender發(fā)送郵件的方法示例(附源碼)
- spring mail借助qq郵箱服務(wù)器發(fā)送郵件
- Spring學(xué)習(xí)筆記3之消息隊列(rabbitmq)發(fā)送郵件功能
- Java的Spring框架中實現(xiàn)發(fā)送郵件功能的核心代碼示例
- spring+maven實現(xiàn)發(fā)送郵件功能
相關(guān)文章
有關(guān)Java常見的誤解小結(jié)(來看一看)
下面小編就為大家?guī)硪黄嘘P(guān)Java常見的誤解小結(jié)(來看一看)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05Spring Boot與RabbitMQ結(jié)合實現(xiàn)延遲隊列的示例
本篇文章主要介紹了Spring Boot與RabbitMQ結(jié)合實現(xiàn)延遲隊列的示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11線程池調(diào)用kafka發(fā)送消息產(chǎn)生的內(nèi)存泄漏問題排查解決
這篇文章主要為大家介紹了線程池調(diào)用kafka發(fā)送消息產(chǎn)生的內(nèi)存泄漏問題排查解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08Java8 LocalDateTime極簡時間日期操作小結(jié)
這篇文章主要介紹了Java8-LocalDateTime極簡時間日期操作整理,通過實例代碼給大家介紹了java8 LocalDateTime 格式化問題,需要的朋友可以參考下2020-04-04