Use Javamail to send emails, the required jar package (please download the source file of javamail, the official download page: http://www.oracle.com/technetwork/java/javamail/index-138643.html):
mailapi.jar. Defines the interface API used to send and receive emails;
smtp.jar. Contains the class used to send emails;
pop3.jar. Includes the class used to receive emails;
The protocol we usually use to send emails is the SMTP protocol, and the protocol we use to accept emails is the pop3 protocol. Or, we directly add mail.jar to the project, which contains all interfaces and classes for java sending and receiving mail.
Commonly used classes:
Send an email
Below, I will first list the simplest small test example of sending emails in Java:
import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * * QQ(mail.qq.com):POP3 server (port 995) SMTP server (port 465 or 587). * */ public class Demo1 { /** * @param args * @throws MessagingException */ public static void main(String[] args) throws MessagingException { String sendUserName = "[email protected]"; String sendPassword = "pwd"; Properties properties = new Properties(); properties.setProperty("mail.smtp.auth", "true");//The server needs to authenticate properties.setProperty("mail.transport.protocol", "smtp");//Declare the port used to send the email Session session = Session.getInstance(properties); session.setDebug(true);//Agree to print the conversation information with the server on the console of the current thread Message message = new MimeMessage(session);//Construct the sent message message.setText("Hello, I'm Champion.Wong!");//Information content message.setFrom(new InternetAddress("[email protected]"));//Sender Transport transport = session.getTransport(); transport.connect("smtp.126.com", 25, sendUserName, sendPassword);//Connect the sender server transport.sendMessage(message, new Address[]{new InternetAddress("[email protected]")});//Accept email transport.close(); } }Generally, we use Authenticator to encapsulate the username and password, which is opaque! so:
import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.Address; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import junit.framework.TestCase; /** * javamail Send email* @author Championship Wong * Message.addRecipient(Message.Recipient recipient, Address address); Specify the roles of the recipient and the recipient when sending an email* Message.RecipientType.TO Recipient* Message.RecipientType.CC Cc, that is, copy one to another person when sending an email, without replying! However, the recipient above can see who you copied to * Message.RecipientType.BCC sends secretly, and it is also to send a copy to another person when sending an email. However, unlike the above, the recipient cannot see who you secretly gave to * */ public class Demo2 extends TestCase { private static final String sendUserName = "[email protected]";// The username of the server that needs to be connected to send an email private static final String sendPassword = "pwd";// The password of the server that needs to be connected to send an email private static final String sendProtocol = "smtp";// port used to send mail private static final String sendHostAddress = "smtp.126.com";// The address of the server used to send mail public void test() throws AddressException, MessagingException { Properties properties = new Properties(); properties.setProperty("mail.smtp.auth", "true");// The server needs to authenticate properties.setProperty("mail.transport.protocol", sendProtocol);// Declare the port used to send mail properties.setProperty("mail.host", sendHostAddress);// The server address for sending the mail Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(sendUserName, sendPassword); } }); session.setDebug(true);//Print real-time information about sending the mail in the background Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setSubject("Demo2JavaCode sending email test, using Authenticator");// Set the topic message.setRecipients(Message.RecipientType.TO, InternetAddress .parse("[email protected],[email protected]"));// Send message.setRecipients(Message.RecipientType.CC, InternetAddress .parse("[email protected]"));// Cc message .setContent( "<span style="font-size:20px; color:#FFCCFF" mce_style="font-size:20px; color:#FFCCFF">If you see it, it proves that the test was successful! </span>", "text/html;charset=gbk"); Transport.send(message);//Send email} } We send a relatively complex email, including attachments, pictures and texts:
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * * @author Administrator Mr XP.Wang * MimeMultipart The general container of email is Multipart, which defines methods to add and delete various parts of the email. * However, it is an abstract class, and its subclass MimeMultipart needs to be used for MimeMessage object* MimeBodyPart is a subclass of BodyPart specifically used for mimeMessage. The MimeBodyPart object represents a * every part of the mimeMultipart object* MimeUtility.encodeText(String cn) is used to solve the problem of Chinese garbled code in the header information in the email* */ public class Demo3_test { public static void main(String[] args) throws Exception { Properties properties = new Properties(); properties.setProperty("mail.smtp.auth", "true");// The server needs to authenticate properties.setProperty("mail.transport.protocol", "smtp");// Declare the port used to send mail properties.setProperty("mail.host", "smtp.126.com");// The server address of the sending mail Session session = Session.getInstance(properties, new Authenticator() { String sendUserName = "[email protected]"; String sendPassword = "pwd"; protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(sendUserName, sendPassword); } }); session.setDebug(true); MimeMessage msg = new MimeMessage(session);// Declare an email body msg.setFrom(new InternetAddress("/""+MimeUtility.encodeText("Mr XP.Wang")+"/"<[email protected]>")); msg.setSubject("This is my first complicated email");//Set the email subject msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(MimeUtility.encodeText("Wang Xiangpan")+"<[email protected]>,"+MimeUtility.encodeText("Sanmao")+"<[email protected]>")); MimeMultipart msgMultipart = new MimeMultipart("mixed");// Indicate the combination relationship of the email, the mixed relationship msg.setContent(msgMultipart);// Set the email body MimeBodyPart attach1 = new MimeBodyPart();// Attachment 1 MimeBodyPart attach2 = new MimeBodyPart();// Attachment 2 MimeBodyPart content = new MimeBodyPart();// The text of the email, a mixture (picture + text) // Set the attachment and the text into this email body msgMultipart.addBodyPart(attch1); msgMultipart.addBodyPart(attch2); msgMultipart.addBodyPart(content); // Set the first attachment DataSource ds1 = new FileDataSource("F:/ACCP5.0/file/ssh configuration.txt");// Specify the data source of the attachment DataHandler dh1 = new DataHandler(ds1);// Attachment information attached attch1.setDataHandler(dh1);// Specify the attachment attch1.setFileName("ssh.txt"); // Set the second attachment DataSource ds2 = new FileDataSource("resource/48.jpg");// Specify the data source of the attachment DataHandler dh2 = new DataHandler(ds2);// Attachment information attach2.setDataHandler(dh2);//Specify attachment attach2.setFileName("48.jpg"); //Set the text of the email MimeMultipart bodyMultipart = new MimeMultipart("related");//Dependency content.setContent(bodyMultipart);//Specify body MimeBodyPart htmlPart = new MimeBodyPart(); MimeBodyPart gifPart = new MimeBodyPart(); bodyMultipart.addBodyPart(htmlPart); bodyMultipart.addBodyPart(gifPart); DataSource gifds = new FileDataSource("resource/48.jpg");//Set the picture of the text DataHandler gifdh = new DataHandler(gifds); gifPart.setHeader("Content-Location", "http://mimg.126.net/logo/126logo.gif"); gifPart.setDataHandler(gifdh);//Set the picture of the text htmlPart.setContent("I'm just here to make a soy sauce, this is my image photo! <img src="/" mce_src="/""http://mimg.126.net/logo/126logo.gif/">", "text/html;charset=gbk");//Set the text msg.saveChanges();//Save the email//Save the email as a file OutputStream ops = new FileOutputStream("C:/Users/Administrator/Desktop/test.eml"); msg.writeTo(ops); ops.close(); Transport.send(msg); } } Receive emails
Example: Rose collects the latest email.
import java.util.Date;import java.util.Properties;import javax.mail.Folder;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.NoSuchProviderException;import javax.mail.Session;import javax.mail.Store;public class FetchMail { public static void main(String[] args) { String protocol = "pop3"; boolean isSSL = true; String host = "pop.163.com"; int port = 995; String username = "[email protected]"; String password = "rose"; Properties props = new Properties(); props.put("mail.pop3.ssl.enable", isSSL); props.put("mail.pop3.host", host); props.put("mail.pop3.port", port); Session session = Session.getDefaultInstance(props); Store store = null; Folder folder = null; try { store = session.getStore(protocol); store.connect(username, password); folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); int size = folder.getMessageCount(); Message message = folder.getMessage(size); String from = message.getFrom()[0].toString(); String subject = message.getSubject(); Date date = message.getSentDate(); System.out.println("From: " + from); System.out.println("Subject: " + subject); System.out.println("Date: " + date); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } finally { try { if (folder != null) { folder.close(false); } if (store != null) { store.close(); } } catch (MessagingException e) { e.printStackTrace(); } } System.out.println("Received! "); }}