Send mail - Java Foundation

**Preface: * * in fact, when I wrote this article, my heart was very complex, so the main part of this article recorded ...

**Preface: * * in fact, when I wrote this article, my heart was very complex, so the main part of this article recorded my reflection, because there were not many knowledge points of sending e-mail, so a little routine, and the template can be used directly. I put it at the bottom of the article.

I can't resist temptation. Now it's 23:47. Two roommates are playing games and one roommate is learning teaching materials. Yes, the day after tomorrow is 10.30. I also reported for teaching materials, but so far, I only learned section 3 and section 1, and I just went through it briefly. I didn't take time to recite knowledge points and practice questions... How to say? People are inert, and so am I. in the summer vacation, I am at home alone, and my work and rest are very regular. I won't feel boring when listening to online classes and typing codes every day. I really studied very seriously at that time. I thought this state would last for a long time. I also imagined working hard after school: going to bed on time at night, and then getting up early in the morning to study. But imagination is imagination after all. After school, I did knock the code according to my habit at home for several days, but in these days, I started my laziness again. Let's count my serious study time as a week (actually only two or three days). We started school on October 8. Now it's October 28. I was studying the previous week, and for the remaining two weeks, I slept until more than 8 o'clock in the morning and played until 2:30 at night. I was sleepy during the day, as if I had returned to high school. I hate myself, but I succumb to reality again. Yes, I can't resist temptation. If a little attracts me, I'll let myself go.

Why do you want to take the examination of teaching resources?. It was already more than eight o'clock when I got up this morning. The first thing to do when I got up was to sit at the table and do some sets of teaching capital test papers. Yes, I will take the teaching capital test the day after tomorrow, but I didn't panic. It's not because I've reviewed well, but because I've prepared for the test. During this time, I also wanted to think about my future. Does my failure have anything to do with the examination of teaching resources? The answer is yes, but it doesn't matter. Then I have to consider a question: * * why do you want to take the teaching capital examination** The initial idea was to give yourself a way back, because programmers are a fan of age. With the increase of age, their learning ability and memory will decline. In this way, they will be at a disadvantage in the process of the company and job hunting. At this time, many programmers will choose to change careers. Of course, a small number of people will survive in the competition. The result is: I shouldn't apply for teaching resources

I shouldn't have applied for teaching resources. Why shouldn't I apply for teaching resources? Because in my mind, I never planned to be a teacher, and I never wanted to be a teacher from beginning to end. Applying for teaching resources is a blind follow-up behavior. This is not to justify my behavior, but my idea has always been like this, but sometimes the idea is very chaotic. Sometimes I don't know what I think and what I want. Why haven't I always wanted to be a teacher? First: the job of teacher is not very free. The job I like should be free; Second: there is a bottleneck in the teacher industry and there is no innovation, but I like innovation very much and always have some ideas to realize; Third: the salary of teachers is stable but not high. As a boy, if he wants to support his family, he can't rely on the dead salary of teachers alone. After all, a family must support themselves. From these three points, the reasons for not being a teacher are basically clear, so I really don't worry about the exam the day after tomorrow.

* * should I slack off on the UGC exam** The answer is no, although I'm not worried about the test results, I'm also prepared for a little time. Although I don't have much knowledge, the consumption of time is really a waste of time if I don't seek a result, so I won't slack off in this test, and I should pay great attention to it as an opportunity to test myself. So, tomorrow I will try my best to review the sprint on the last day

Peeping into my heart's true thoughts, I've been speculating about my heart. Do I want to take the postgraduate entrance examination? I've always been confused. I believe you will be in a confused state at this stage. Our major is easy to find a job, especially those who master cutting-edge technology. I like typing code very much (I didn't like it before). Whenever I type out the program I want, I have a sense of achievement. So do I concentrate on technology or take the postgraduate entrance examination? To be honest, I don't want to take the postgraduate entrance examination. I really want to concentrate on studying the code, and then step into the society to find a job. But now many high paid positions require academic qualifications. I really don't understand. If a person's technology really reaches a certain level, does it have anything to do with his own academic qualifications? My family has always told me about the postgraduate entrance examination, saying that in today's society, college students are everywhere, and it's impossible not to take the postgraduate entrance examination. In this way, I have been very tangled, I sometimes tell myself, I still take the postgraduate entrance examination, very helpless, really helpless. I really want to prove that I can fight my own world without taking the postgraduate entrance examination, but I don't have the courage, because I know this is the reality and the real society.

* * I intend to take the postgraduate entrance examination and not compromise this society** Do you have to give up your current technical research? Many people told me that if you plan to take the postgraduate entrance examination, you should prepare for the postgraduate entrance examination now. Don't study any cutting-edge technology and turn new to take the postgraduate entrance examination. I don't know. Studying technology is my interest. Learning without interest is like walking dead. It's a rereading machine without emotion. I don't want to be a machine. I want to take the postgraduate entrance examination while studying. Of course, I still spend most of my time preparing for the postgraduate entrance examination. I haven't worked out the specific plan yet, but the preliminary idea is to seriously prepare for the postgraduate entrance examination, improve my technology and ensure that I don't fall behind.

* * how to resist temptation** As mentioned above, a little temptation makes me free myself, but how can I calm down and learn when I am at home? People are different. Some people can't stand loneliness and need company in learning. Some people are quieter and calmer, and I should be the latter. Therefore, when I set goals and detailed test preparation plans, I will go out to rent a house and study quietly alone. During this time, I also want to make it clear that big guys are always lonely. Although I am not a big man, I also have a little experience of this sentence. When you know more, you will find it difficult to find a person who can communicate with you, or even not a person who can communicate with you at all.

After reflection, here is the note code for sending email

Use the obtained jar package

<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
1, Create a message and save it locally
package cn.daitools; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Date; import java.util.Properties; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; //Create a message /** * * java Realize the function of sending mail from mailbox * * * @author WQ * */ public class demo01 { public static void main(String[] args) throws Exception { // 1. Create a message Properties props = new Properties(); // Parameter configuration for connecting to the mail server (only required when sending mail) Session session= Session.getInstance(props); // Create a session object (prepared for sending mail) according to the parameter configuration MimeMessage message = new MimeMessage(session); // Create mail object /* * You can also create MimeMessage objects from existing eml mail files * MimeMessage message = new MimeMessage(session, new FileInputStream("MyEmail.eml")); */ // 2. From: sender // The three parameters of Internet address are: mailbox, displayed nickname (only for display, no special requirements), and character set code of nickname // When you really want to send, the mailbox must be a real and valid mailbox. message.setFrom(new InternetAddress("[email protected]", "USER_AA", "UTF-8")); // 3. To: recipient message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("[email protected]", "USER_CC", "UTF-8")); // To: add recipients (optional) message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("[email protected]", "USER_DD", "UTF-8")); // Cc: Cc (optional) message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("[email protected]", "USER_EE", "UTF-8")); // Bcc: Bcc (optional) message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("[email protected]", "USER_FF", "UTF-8")); // 4. Subject: email subject message.setSubject("TEST Mail subject", "UTF-8"); // 5. Content: message body (html tag can be used) message.setContent("TEST This is the body of the message...", "text/html;charset=UTF-8"); // 6. Set the displayed sending time message.setSentDate(new Date()); // 7. Save the previous settings message.saveChanges(); // 8. Save the message locally OutputStream out = new FileOutputStream("MyEmail.eml"); message.writeTo(out); out.flush(); out.close(); } }
2, Send ordinary mail
package cn.daitools; import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.*; import javax.mail.internet.*; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Properties; public class demo02 { public static void main(String[] args) throws GeneralSecurityException, MessagingException, UnsupportedEncodingException { //Configure mailbox connection information Properties prop = new Properties(); prop.setProperty("mail.host","smtp.qq.com"); prop.setProperty("mail.transport.protocol","smtp"); prop.setProperty("mail.smtp.auth","true"); //Set ssl encryption MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable","true"); prop.put("mail.smtp.ssl.socketFactory",sf); //1. Create a seeion environment for sending mail Session session = Session.getDefaultInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { //Sender, authorization code return new PasswordAuthentication("[email protected]","tujcblipdrbngaef"); } }); // //Turn on the Debug mode for sending mail // session.setDebug(true); //2. Get the transport object through the Session object Transport ts = session.getTransport(); //3. Use the user name and authorization code to connect to the mailbox server ts.connect("smtp.qq.com","[email protected]","tujcblipdrbngaef"); //4. Create message //Session needs to be passed MimeMessage message = new MimeMessage(session); //Indicate sender message.setFrom(new InternetAddress("[email protected]","Website registration","utf-8")); //Indicates the recipient of the message message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]")); //Set the title of the message message.setSubject("Verification Code"); //Prepare body data MimeBodyPart textbody = new MimeBodyPart(); textbody.setContent("code","text/html;charset=utf-8"); //Describe data relationships MimeMultipart mm =new MimeMultipart(); mm.addBodyPart(textbody); mm.setSubType("related"); //Set the assembled mm picture and text as the theme MimeBodyPart contentText = new MimeBodyPart(); contentText.setContent(mm); //Set the message and save the changes message.setContent(mm); message.saveChanges(); //5. Send mail ts.sendMessage(message,message.getAllRecipients()); //6. Close connection ts.close(); } }
3, Optimize code structure
package cn.daitools; import com.sun.mail.util.MailSSLSocketFactory; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; /*Send a simple email*/ public class demo03 { public static void main(String[] args) throws Exception { /*Configure basic information*/ String fromAddress = "[email protected]"; /*Sender*/ String token = "tujcblipdrbngaef"; /*Authorization code*/ String toAddress = "[email protected]"; /*addressee*/ String mailHost = "smtp.qq.com"; /*Mailbox server*/ /*Create an object that represents the information of the mail server*/ Properties prop = new Properties(); prop.setProperty("mail.host", "smtp.qq.com"); //Set up QQ mail server prop.setProperty("mail.transport.protocol", "smtp"); // Mail sending protocol prop.setProperty("mail.smtp.auth", "true"); // User name and password need to be verified /*Perform ssl security verification*/ MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); /*Creating a Session object can be imagined as a mobile phone card*/ Session session = Session.getDefaultInstance(prop, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { //Sender mail user name and authorization code return new PasswordAuthentication(fromAddress, token); } }); //Turn on the debug mode of Session, so that you can view the running status of the Email sent by the program session.setDebug(true); /*Obtaining an object through Session to send messages can be understood as obtaining a mobile phone with a mobile phone card inserted*/ Transport ts = session.getTransport(); ts.connect(mailHost,fromAddress,toAddress); /*I got my cell phone. Now I can send mail * Create a message*/ MimeMessage msg = new MimeMessage(session); /*Indicate sender*/ msg.setFrom(new InternetAddress(fromAddress,"stupid","utf-8")); /*Indicate recipients*/ msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(toAddress)); /*Set the title of the message*/ msg.setSubject("Simple mail test"); /*Set the content of the message*/ msg.setContent("Hello, I'm a fool","text/html;charset=utf-8"); /*Send mail*/ ts.sendMessage(msg,msg.getAllRecipients()); /*Close connection*/ ts.close(); } }
4, Send a graphic email
package cn.daitools; import com.sun.mail.util.MailSSLSocketFactory; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Authenticator; 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.MimeMultipart; import java.io.FileReader; import java.util.Properties; //Send text + picture public class demo04 { public static void main(String[] args) throws Exception { /*Configure basic information*/ String fromAddress = "[email protected]"; /*Sender*/ String token = "tujcblipdrbngaef"; /*Authorization code*/ String toAddress = "[email protected]"; /*addressee*/ String mailHost = "smtp.qq.com"; /*Mailbox server*/ /*Create an object that represents the information of the mail server*/ Properties prop = new Properties(); prop.setProperty("mail.host", "smtp.qq.com"); //Set up QQ mail server prop.setProperty("mail.transport.protocol", "smtp"); // Mail sending protocol prop.setProperty("mail.smtp.auth", "true"); // User name and password need to be verified /*Perform ssl security verification*/ MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); /*Creating a Session object can be imagined as a mobile phone card*/ Session session = Session.getDefaultInstance(prop, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { //Sender mail user name and authorization code return new PasswordAuthentication(fromAddress, token); } }); //Turn on the debug mode of Session, so that you can view the running status of the Email sent by the program session.setDebug(true); /*Obtaining an object through Session to send messages can be understood as obtaining a mobile phone with a mobile phone card inserted*/ Transport ts = session.getTransport(); ts.connect(mailHost,fromAddress,toAddress); /*I got my cell phone. Now I can send mail * Create a message*/ MimeMessage msg = new MimeMessage(session); /*Indicates the sender's address, sender's nickname, and encoding object*/ msg.setFrom(new InternetAddress(fromAddress,"daidai","utf-8")); /*Indicate recipients*/ msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(toAddress)); /*Set the title of the message*/ msg.setSubject("Simple mail test"); /*Set the content of the message*/ /*============================*/ /*Create a part of the message as a picture*/ final MimeBodyPart body1 = new MimeBodyPart(); body1.setDataHandler(new DataHandler(new FileDataSource("img/1.png"))); body1.setContentID("1.png"); /*Prepare body data*/ final MimeBodyPart body2 = new MimeBodyPart(); body2.setContent("<img src='cid:1.png'>","text/html;charset=utf-8"); /*Describe data relationships*/ final MimeMultipart context = new MimeMultipart(); context.addBodyPart(body2); context.addBodyPart(body1); context.setSubType("related"); /*Set to the message and save the changes*/ msg.setContent(context); msg.saveChanges(); /*============================*/ /*Send mail*/ ts.sendMessage(msg,msg.getAllRecipients()); /*Close connection*/ ts.close(); } }
5, Send an email with attachments

Note: due to some protocol rules, the size of attachments is limited within 20m, so attachments above 20m will report exceptions

package cn.daitools; import com.sun.mail.util.MailSSLSocketFactory; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.*; import java.util.Properties; //Send attachments public class demo05 { public static void main(String[] args) throws Exception { /*Configure basic information*/ String fromAddress = "[email protected]"; /*Sender*/ String token = "tujcblipdrbngaef"; /*Authorization code*/ String toAddress = "[email protected]"; /*addressee*/ String mailHost = "smtp.qq.com"; /*Mailbox server*/ /*Create an object that represents the information of the mail server*/ Properties prop = new Properties(); prop.setProperty("mail.host", "smtp.qq.com"); //Set up QQ mail server prop.setProperty("mail.transport.protocol", "smtp"); // Mail sending protocol prop.setProperty("mail.smtp.auth", "true"); // User name and password need to be verified /*Perform ssl security verification*/ MailSSLSocketFactory sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); /*Creating a Session object can be imagined as a mobile phone card*/ Session session = Session.getDefaultInstance(prop, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { //Sender mail user name and authorization code return new PasswordAuthentication(fromAddress, token); } }); //Turn on the debug mode of Session, so that you can view the running status of the Email sent by the program session.setDebug(true); /*Obtaining an object through Session to send messages can be understood as obtaining a mobile phone with a mobile phone card inserted*/ Transport ts = session.getTransport(); ts.connect(mailHost,fromAddress,toAddress); /*I got my cell phone. Now I can send mail * Create a message*/ MimeMessage msg = new MimeMessage(session); /*Indicates the sender's address, sender's nickname, and encoding object*/ msg.setFrom(new InternetAddress(fromAddress,"daidai","utf-8")); /*Indicate recipients*/ msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(toAddress)); /*Set the title of the message*/ msg.setSubject("Simple mail test"); /*Set the content of the message*/ /*============================*/ /*Create a part of the message as a picture*/ final MimeBodyPart body1 = new MimeBodyPart(); body1.setDataHandler(new DataHandler(new FileDataSource("img/1.png"))); body1.setContentID("1.png"); /*Prepare body data*/ final MimeBodyPart body2 = new MimeBodyPart(); body2.setContent("<img src='cid:1.png'>","text/html;charset=utf-8"); /*Encapsulate graphic information*/ final MimeMultipart context = new MimeMultipart(); context.addBodyPart(body2); context.addBodyPart(body1); context.setSubType("related"); /*Set text as part of content*/ final MimeBodyPart body3 = new MimeBodyPart(); body3.setContent(context); /*Add an attachment*/ final MimeBodyPart body4 = new MimeBodyPart(); body4.setDataHandler(new DataHandler(new FileDataSource("D:\\desktop\\To be sorted out\\Tiktok download assistant V1.0.zip"))); body4.setFileName(MimeUtility.encodeText("Tiktok download assistant V1.0.zip")); //Use the toolkit for file name transcoding to prevent Chinese random code /*Finally, encapsulate the whole mail information*/ final MimeMultipart mail = new MimeMultipart(); mail.addBodyPart(body3); mail.addBodyPart(body4); mail.setSubType("mixed"); /*Set to the message and save the changes*/ msg.setContent(mail); msg.saveChanges(); /*============================*/ /*Send mail*/ ts.sendMessage(msg,msg.getAllRecipients()); /*Close connection*/ ts.close(); } }

That's the end of today's record. Good night!

28 October 2021, 14:21 | Views: 6012

Add new comment

For adding a comment, please log in
or create account

0 comments