스프링 부츠는 무엇입니까?
Spring Boot는 Spring Applications의 초기 구성 구성 및 개발 프로세스를 단순화하도록 설계된 프레임 워크입니다. 이 프레임 워크는 특정 구성 방법을 사용하므로 개발자가 보일러 플레이트 구성을 정의 할 필요가 없습니다.
스프링 부츠의 이점
1. 간단한 구성;
2. 간단한 인코딩;
3. 간단한 배포;
4. 간단한 모니터링;
개요
Spring Boot는 메일 서버를 통합하고 Spring Boot를 사용하면 이메일 전송을 쉽게 달성 할 수 있습니다. 스프링 부츠에 대한 최근 이메일 보내기 및 예방 조치를 정렬하십시오.
Maven 패키지 종속성
<pectionency> <groupid> org.springframework.boot </groupid> <artifactid> 스프링 부트 스타터-메일 </artifactid> </fectionency>
스프링 부팅 구성
spring.mail.host = smtp.servie.comspring.mail.username = username // sender의 이메일 주소 spring.mail.password = qq mailbox의 password //, 암호는 발신자의 인증 코드 spring.mail.properties.mail.smtp.smtp.mail.properties.mail.smtp. #암호화 된 전송을 활성화하기 위해 프로토콜 확인 항목 spring.mail.properties.mail.smtp.starttls.required = fasle #whether 암호화 된 전송을 활성화하려면 프로토콜 확인 항목 spring.mail.password는 메일 박스 설정에서 생성 해야하는 권한이없는 권한 코드입니다.
스프링 코드 구현
package com.dbgo.webserviceedemo.email; import org.springframework.beans.beans.annotation.autowired; import org.springframework.core.io.filesystemresource; import org.sprameframework.mail.javamail.javamailsender; import org.springframework.mail.javamail.mimemessagehelper; import org.sprameframework.stereotyp.component; import javax.mail.messagingexception; import javax.mail.internet.mimemessage; import java.io.file; @componter ( "emailtool") Javamailsender; public void sendsimplemail () {mimemessage message = null; try {message = javamailsender.createmimemessage (); MimemessageHelper 도우미 = New MimemessageHelper (메시지, True); Helper.setfrom ( "[email protected]"); Helper.setto ( "[email protected]"); Helper.setSubject ( "제목 : HTML 컨텐츠 보내기"); StringBuffer sb = new StringBuffer (); sb.append ( "<H1> 큰 Title-H1 </h1>") .Append ( "<p style = 'color :#f00 '> 빨간색 단어 </p>") .append ( "<p style ='text-align : right '> right </p>"); Helper.settext (sb.tostring (), true); FileSystemResource filesystemresource = new FileSystemResource (새 파일 ( "d : /76678.pdf")) hel javamailsender.send (메시지); } catch (MessagingException e) {e.printstacktrace (); }}}비 스프링 부츠에서 이메일 보내기 :
Maven 패키지 종속성
<pectionies> <pectionency> <groupId> com.sun.mail </groupId> <artifactid> javax.mail </artifactid> <버전> 1.5.2 </version> </fectionency> </fectionencies>
Demo1 코드 예제
package com.justin.framework.core.utils.email; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.io.ioexception; import java.io.inputstream; java.io java.util.date; import java.util.properties; import javax.activation.datahandler; import javax.activation.datasource; import javax.activation.filedatasource; import javax.mail.address; import javax.mail.authenticator; import javax.mail.message; message; javax.mail.message.recipienttype; import javax.mail.message.recipienttype; import javax.mail.messagingException; import javax.mail.passwordauthentication; import javax.mail.session; import javax.mail.transport; import javax.mail.internetet.interaddress; javax.mail.internet.mimebodypart; import javax.mail.mail.internet.mimemessage; import javax.mail.internet.mimemultipart; import javax.mail.internet.mimeutility;/*** SMTP 프로토콜을 사용하여 이메일 보내기*/public sendpocode {// public sendpp ""smtp protoco {; // smtp mail server 개인 최종 정적 문자열 호스트 = "mail.tdb.com"; // SMTP 메일 서버 기본 포트 프라이빗 최종 정적 문자열 포트 = "25"; // 인증이 필요한지 여부 개인 최종 정적 문자열 is_auth = "true"; // 디버그 모드 활성화 여부 (클라이언트와 서버가 상호 작용할 때 질문의 응답 메시지와 답변을 인쇄 할 디버그 모드 활성화) 비공개 최종 정적 문자열 IS_ENABLED_DEBUG_MOD = "true"; // sender private static string from = "[email protected]"; // 수신자 개인 정적 문자열 to = "[email protected]"; 개인 정적 문자열 sendusername = "[email protected]"; 개인 정적 문자열 senduserpwd = "New*2016"; // 메일 서버에 연결하는 세션 정보를 초기화 개인 정적 속성 props = null; static {props = new Properties (); props.setProperty ( "mail.enable", "true"); props.setProperty ( "mail.transport.protocol", 프로토콜); props.setProperty ( "mail.smtp.host", 호스트); props.setProperty ( "mail.smtp.port", 포트); props.setProperty ( "mail.smtp.auth", is_auth); // 상황에 따라 props.setproperty ( "mail.debug", is_enabled_debug_mod); } / *** 간단한 텍스트 메일 보내기* / public static boolean sendTextEmail (string to, int code)은 예외 {try {// 세션 인스턴스 개체 세션 세션 1 = session.getDefaultInstance (props); // mimemeSage 인스턴스 생성 객체 mimemessage message = new Mimemessage (session1); // 발신자 메시지를 설정합니다. // 이메일 주제 메시지를 설정합니다 .SetSubject ( "내 연소 엔진 등록 검증 코드"); // 수신자 메시지를 설정합니다. // 보내기 시간 보내기 메시지를 설정합니다 .SetSentDate (새 날짜 ()); // 일반 텍스트 내용을 이메일 문자 메시지로 설정합니다 .settext ( "귀하의 확인 코드는"+Code+"입니다. 확인 코드는 10 분 동안 유효합니다. 만료 된 후에 다시 구입하십시오!"+"China Internal Combustion Engine Society"); // 최종 이메일 내용을 저장하고 생성합니다. SaveChanges (); // 전송 인스턴스를 가져옵니다 객체 전송 전송 = 세션 1.getTransport (); // 연결을 엽니 다. // 메시지 객체를 전송 객체에 전달하고 메시지를 전송하여 전송합니다 .SendMessage (메시지, 메시지 .getallRecipients ()); // 연결을 닫습니다. 진실을 반환하십시오. } catch (예외 e) {e.printstacktrace (); 거짓을 반환합니다. }} public static void main (string [] args)은 예외 {sendhtmlemail ( "[email protected]", 8888); } / *** 간단한 html 이메일 보내기* / public static boolean sendhtmlemail (string to, int code) 예외 {// 세션 객체 생성 세션 세션 1 = session.getInstance (props, new myauthenticator ()); // mimemeSage 인스턴스 생성 객체 mimemessage message = new Mimemessage (session1); // 이메일 주제 메시지를 설정합니다 .SetSubject ( "내 연소 엔진 등록"); // SET Sender Message.SetFrom (새 InternetAdDress (From)); // 보내기 시간 메시지를 설정합니다 .SetSentDate (새 날짜 ()); // 수신자 메시지를 설정합니다. // HTML 컨텐츠를 이메일 본문으로 설정하고 MIME 유형을 Text/HTML 유형으로 지정하고 GBK Messag </p> <p style = '텍스트 : 2em'> 이번에는 내부 연소 엔진 계정을 등록하고 있습니다 사회 </p> </div> ","text/html; charset = utf-8 "); // 사용자 정의 발신자 닉네임 string nick = ""를 설정합니다. try {nick = javax.mail.internet.mimeutility.encodetext ( "China Internal Combustion Engine Society"); } catch (UnsupportedEncodingException e) {e.printstacktrace (); } message.setfrom (new InternetAddress (nick+"<"+from+">"); // 최종 이메일 내용을 저장하고 생성합니다. SaveChanges (); // 이메일 보내기 try {rangplity.send (메시지); 진실을 반환하십시오. } catch (예외 e) {e.printstacktrace (); 거짓을 반환합니다. }} / *** 임베디드 이미지가 포함 된 HTML 메일을 보내십시오* / public static void sendhtmlwithinnerimageEmail ()가 메시징 exception {// 세션 인스턴스 객체 객체 세션 = session.getDefaultInstance (props, new myAuthenticator ()); // 이메일 내용 만들기 mimemessage message = new Mimemessage (세션); // 메일 주제 및 인코딩 형식 메시지를 지정하십시오. // sender message.setfrom (new InternetAddress (from)); // Receptient Message.setRecipients (recepientType.to, InternetAddress.parse (to)); // cc message.setRecipient (RecepitientType.cc, new InternetAddress ( "[email protected]"); // 비밀 보내기 (이메일 수신자 목록에 표시되지 않음) 메시지. // 시간 메시지 보내기 .SetSentDate (새 날짜 ()); // mime subtype "관련"mimemultipart mp = new Mimemultipart ( "relation")로 mimemultipart 객체를 만듭니다. // 신체를 나타내는 MimeBodyPart 객체를 만들어 mimeMultipart 객체에 추가하여 mimebodypart htmlpart = new MimebodyPart (); mp.addbodypart (htmlpart); // 이미지 리소스를 나타내는 MimeBodyPart 객체를 작성하여 mimemultipart 객체에 추가 mimebodypart imagePart = new MimeBodyPart (); mp.addbodyPart (imagePart); // MIMEMULTIPART 객체를 전체 메시지의 내용으로 설정합니다. // 임베디드 이미지 메일 바디 데이터 소스 DS = New FileDatasource (새 파일 ( "resource/firefoxlogo.png")을 설정합니다. Datahandler DH = 새로운 Datahandler (DS); ImagePart.SetDataHandler (DH); ImagePart.setContentId ( "Firefoxlogo.png"); // 다른 메일 바디 참조에 사용할 내용 번호를 설정하십시오. // MIME 하위 유형 "대안"이있는 MimemultIPART 객체를 작성하고 이전에 생성 된 HTMLPART 객체의 이메일 컨텐츠 역할을합니다. htmlmultipart = new MimemultIpart ( "대체"); // html body mimebodypart htmlbodypart를 나타내는 mimebodypart 객체를 만듭니다. // 여기서 cid = androidlogo.gif는 참조 메시지의 이미지, 즉 imagePart.setContentId ( "androidlogo.gif"); 메소드 htmlbodypart.setContent ( "<span style = 'color : red;'> 이것은 이미지가 포함 된 html 이메일입니다 !!! <img src =/"cid : firefoxlogo.png/"/> </span>", "text/html; charset = utf-8"); htmlmultipart.addbodypart (htmlbodypart); htmlpart.setContent (htmlmultipart); // 최종 이메일 내용을 저장하고 생성합니다. SaveChanges (); // 메일 전송 전송 (메시지); } / *** 내장 된 그림, 첨부 파일, 다수의 수신자 (사서함 이름 표시), 이메일 우선 순위 및 영수증을 읽는 완전한 HTML 메시지를 보내십시오* / public static void sendMultipleEmail () 예외 {String charset = "utf-8"; // 중국인 인코딩 형식을 지정 // 세션 생성 인스턴스 객체 객체 세션 세션 = 세션 (propss, new myauthenticator ()); // mimemessage 생성 인스턴스 객체 mimemessage message = new Mimemessage (세션); // 주제 메시지를 설정합니다. // SET Sender Message.SetFrom (새 InternetAdDress (From, "Sina Test 이메일", charset)); // set receptient message.setRecipients (recepientType.to, 새 주소 [] {// 매개 변수 1 : 이메일 주소, 매개 변수 2 : 이름 (이름 만 이메일 주소가 아닌 클라이언트에 표시됩니다), 매개 변수 3 : 새 InternetAddress ( "[email protected]", "Zhang San_sohu", New) InternetAddress ( "[email protected]", "li si_163", charset),}); // cc message.setRecipient (RecepientType.cc, new InternetAddress ( "[email protected]", "wang wu_gmail", charset); // secret emessure.setRecipient (RecepientType.bcc, new InternetAddress ( "[email protected]", "zhao liu_qq", charset)); // 보내기 시간 메시지를 설정합니다 .SetSentDate (새 날짜 ()); // 답장을 설정합니다 (수신자 가이 이메일에 응답 할 때 기본 수신자가 제공됩니다) 메시지. // 우선 순위 설정 (1 : 비상 3 : 정상 5 : 낮음) 메시지 .SetHeader ( "x-priority", "1"); // 읽기 영수증을 요청합니다 (수신자는 이메일을 읽을 때 발신자가 회신하라는 메시지가 표시되어 이메일이 수신되어 읽었음을 나타냅니다. // mime subtype "mixed"로 mimemultipart 객체를 만듭니다. 이것은 혼합 된 조합 유형 이메일 mimemultipart mailcontent = new mimemultipart ( "mixed")임을 나타냅니다. Message.SetContent (MailContent); // 첨부 파일 MimeBodyPart attach1 = new MimeBodyPart (); MimebodyPart attach2 = New MimeBodyPart (); // content mimebodypart mailbody = new MimebodyPart (); // MailContent.AddBodyPart (attach1)에 첨부 및 내용을 추가합니다. MailContent.addbodyPart (attach2); MailContent.addbodyPart (MailBody); // 첨부 파일 1 (JAF 프레임 워크 사용 메일 바디 생성) DataSource DS1 = New FileDatasource ( "Resource/Earth.bmp"); Datahandler dh1 = 새로운 Datahandler (DS1); att attach1.setdatahandler (dh1); // 첨부 파일 2 DataSource DS2 = New FileDatasource ( "자원/학습 방법 C Language Well.txt"); Datahandler dh2 = 새로운 Datahandler (DS2); att att // 이메일 본문 (임베디드 그림 + html 텍스트) mimemultipart body = new mimemultipart ( "관련"); // 이메일 본문도 조합이며 조합 관계는 MailBody.SetContent (Body)를 지정해야합니다. // 전자 메일 바디는 html로 구성되어 있으며 그림 mimebodypart imgpart = new MimebodyPart (); MimebodyPart htmlPart = New MimeBodyPart (); body.addbodypart (imgpart); body.addbodypart (htmlpart); // 텍스트 이미지 DataSource DS3 = New FileDatasource ( "Resource/Firefoxlogo.png"); Datahandler dh3 = 새로운 Datahandler (DS3); imgpart.setdatahandler (dh3); imgpart.setContentID ( "firefoxlogo.png"); // html 이메일 컨텐츠 mimemultipart htmlmultipart = new Mimemultipart ( "대체"); htmlpart.setContent (htmlmultipart); MimebodyPart htmlContent = New MimeBodyPart (); htmlcontent.setContent ( "<span style = 'color : red'> 이것은 Java 메일로 직접 보낸 이메일입니다!" + "<img src = 'cid : firefoxlogo.png'/> </span>", "text/html; charset = gbk"); htmlmultipart.addbodypart (htmlcontent); // 메시지 내용을 저장하고 message.sevechanges (); /*파일 emml = buildemlfile (메시지); sendMailForEml (eml);*/ // mail transport.send (메시지); }/*** 이메일 내용에 EML 파일을 생성* @param 메시지 이메일 내용*/public static 파일 BuildEmlFile (메시지 메시지)은 MessagingException, filenotFoundException {파일 = 새 파일 ( "c : //" + mimeutility.decodetext (message.getSubject ()) + "); message.writeto (새 fileoutputStream (file)); 반환 파일; } / *** 로컬로 생성 된 이메일 파일 보내기* / public static void sendmailforeml (파일 emml) 예외 {// 이메일 세션 세션 = session.getinstance (props, new myauthenticator ()); // 이메일 컨텐츠를 가져옵니다. 즉, inputStream이 시작되기 전에 생성 된 EML 파일이 = new FileInputStream (eml); mimemessage message = new Mimemessage (세션, IS); // 이메일 전송 전송 (메시지); } / *** 메일 서버에 인증 정보를 제출* / 정적 클래스 myAuthentICator authenticator {private string username = ""; 개인 문자열 비밀번호 = ""; public myauthenticator () {super (); this.password = senduserpwd; this.username = sendusername; } public myauthenticator (문자열 사용자 이름, 문자열 비밀번호) {super (); this.username = username; this.password = 비밀번호; } @override Protected PasswordAuthentication getPasswordAuthentication () {return new passwordAuthentication (사용자 이름, 암호); }}}Demo2 코드 예 :
package com.justin.framework.core.utils.email;import java.util.HashSet;import java.util.Properties;import java.util.Set;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.message; import javax.mail.multipart; import javax.mail.session; import javax.mail.transport; import javax.mail.internet.internetaddress; import javax.mail.internet.mimebodypart; import javax.mail.mailet.mimessage; javax.mail.internet.mimemultipart; import javax.mail.internet.mimeutility; public class mailmanagerutils {// 이메일 보내기 public static boolean sendmail (이메일 email) {string subject = email.getSubject (); 문자열 content = email.getContent (); 문자열 [] Recruits = email.getRecievers (); 문자열 [] Copyright = email.getCopyto (); 문자열 attbody = email.getattbody (); 문자열 [] attbodys = email.getattBodys (); if (recievers == null || collecters.length <= 0) {return false; } try {properties props = new Properties (); props.setProperty ( "mail.enable", "true"); props.setProperty ( "mail.protocal", "smtp"); props.setProperty ( "mail.smtp.auth", "true"); props.setproperty ( "mail.user", "[email protected]"); Props.SetProperty ( "Mail.Pass", "New ***"); props.setProperty ( "mail.smtp.host", "mail.tdb.com"); props.setproperty ( "mail.smtp.from", "[email protected]"); props.setProperty ( "mail.smtp.fromname", "tdbvc"); // 메일 서버 세션과 통신 할 프로그램을 만듭니다. MailConnection = session.getInstance (propss, null); 메시지 msg = 새로운 mimemessage (mailconnection); // SET SET SENTER 및 Receptiend 주소 Sender = New InternetAdDress (Props.GetProperty ( "mail.smtp.from")); // 다수의 수신자 msg.setfrom (sender); <ctentedaddress> touserset = new Hashset <cteteraddress> (); // (int i = 0; i <recevers.length; i ++) {if (recievers [i] .trim (). matches ( "^// w+([-+.] // w+)*@// w+([-.] // w+)+$") {touserset.add (recievers [i])); }} msg.setRecipients (message.recipienttype.to, touserset.toArray (new InternetAddress [0]); // cc if (copyto! = null) {set <cteteraddress> copyTouserSet = new Hashset <InternetAddress> (); // (int i = 0; i <copyto.length; i ++) {if (copyto [i] .trim (). matches ( "^// w+([-+.]/w+)*@// w+([-.] //] // w+))) {copyTouserset.addd (copyto [i])) }} // msg.setRecipients (message.recipienttype.cc, (address []) InternetAddress.parse (copyto)); msg.setRecipients (message.recipienttype.cc, copytouserset.toArray (new InternetAddress [0]); } // 이메일 주제를 설정합니다 Msg.setSubject (mimeUtility.encodetext (주제, "UTF-8", "b"); // 중국어가 달린 코드 문제 // 이메일 내용 설정 BodyPart MessagePart = New MimeBodyPart (); MessageBodyPart.setContent (content, "text/html; charset = utf-8"); // 중국식 멀티 파트 = 새로운 mimemultipart (); multipart.addbodyPart (MessageBodyPart); msg.setContent (multipart); / *********************************/ if (attbody! = null) {string [] filepath = attbody.split ( ";"); for (string filepath : filepath) {// 문자의 첨부 파일을 설정합니다 (로컬 컴퓨터의 파일을 첨부 파일로 사용) BodyPart MDP = New MimeBodyPart (); FileDatasource FDS = New FileDatasource (Filepath); Datahandler DH = 새로운 Datahandler (FDS); mdp.setfilename (mimeUtility.encodetext (fds.getName ())); MDP.SetDatahandler (DH); multipart.addbodyPart (MDP); } // MTP를 메시지 객체 MSG의 내용으로 넣습니다. }; if (attbodys! = null) {for (String FilePath : AttBodys) {// 문자의 첨부 파일을 설정합니다 (로컬 시스템의 파일을 첨부 파일로 사용) BodyPart MDP = New MimeBodyPart (); FileDatasource FDS = New FileDatasource (Filepath); Datahandler DH = 새로운 Datahandler (FDS); mdp.setfilename (mimeUtility.encodetext (fds.getName ())); MDP.SetDatahandler (DH); multipart.addbodyPart (MDP); } // MTP를 메시지 객체 MSG의 내용으로 넣습니다. }; /***************************************************/ //Storage the email first msg.saveChanges(); System.out.println ( "이메일 보내기 ..."); 전송 전송 = MailConnection.GetTransport (Props.GetProperty ( "Mail.Protocal")); // 메일 서버 이름, 사용자 이름, 비밀번호 trans.connect (propss.getProperty ( "mail.smtp.host"), props.getProperty ( "mail.user"), props.getProperty ( "mail.pass")); trans.sendmessage (msg, msg.getallrecipients ()); System.out.println ( "성공적으로 메일 보내기!"); // 채널을 닫습니다. } true를 반환합니다. } catch (예외 e) {System.err.println ( "이메일 보내지 실패!" + e); 거짓을 반환합니다. } 마침내 {}} // 발신자, 수신자 및 응답 소지자가 이메일에서 중국어 코드를 잡았으며, res는 획득 한 주소입니다. http의 기본 인코딩 메소드는 중국어를 포함하는 주소를 보내기 위해 iso8859_1 //입니다. getchinesefrom (String res) {string from = res; try {if (from.startSwith ( "=? gb") || from.startSwith ( "=? gb") || from.startSwith ( "=? utf")) {from = mimeUtility.decodetext (from); } else {from = new String (from.getBytes ( "iso8859_1"), "gbk"); }} catch (예외 e) {e.printstacktrace (); }로 돌아갑니다. } // 공개 정적 문자열 Tochinese (String Strvalue)를 인코딩하는 GBK로 변환 {try {if (strvalue == null) return null; else {strvalue = new String (strvalue.getBytes ( "iso8859_1"), "gbk"); Return Strvalue; }} catch (예외 e) {return null; }} public static void main (string [] args) {이메일 이메일 = 새 이메일 (); email.setRecievers (new String [] { "[email protected]"}); email.setsubject ( "테스트 테스트"); email.setContent ( "테스트 테스트"); sendmail (이메일); }}요약
위는이 기사의 전체 내용입니다. 이 기사의 내용에 모든 사람의 연구 나 작업에 대한 특정 참조 가치가 있기를 바랍니다. 궁금한 점이 있으면 의사 소통을 위해 메시지를 남길 수 있습니다. Wulin.com을 지원 해주셔서 감사합니다.