This article describes the method of Java using JavaMail to send emails. Share it for your reference, as follows:
Code 1. Email_Autherticator.java server verification code
import javax.mail.Authenticator;import javax.mail.PasswordAuthentication;public class Email_Autherticator extends Authenticator { String username = "User name of your email address"; String password = "Password of your email address"; public Email_Autherticator() { super(); } public Email_Autherticator(String user,String pwd){ super(); username = user; password = pwd; } public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(username,password); }}Code 2. Mail.java code to send emails
import java.util.Date;import java.util.Properties;import javax.mail.Address;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.SendFailedException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class Mail { private String host = "smtp.126.com"; private String mail_head_name = "this is head of this mail"; private String mail_head_value = "this is head of this mail"; private String mail_to = "[email protected]"; private String mail_from = "[email protected]"; private String mail_subject = "this is the subject of this test mail"; private String mail_body = "this is mail_body of this test mail"; private String personalName = "My Mail"; public void sendMail() throws SendFailedException{ try { Properties props = new Properties();//Get system environment Authenticator auth = new Email_Autherticator();//Carry mail service user authentication props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); System.out.println(props); Session session = Session.getDefaultInstance(props,auth); //Set session, communicate with the mail server MimeMessage message = new MimeMessage(session); message.setContent("Hello","text/plain");//Set the mail format message.setSubject(mail_subject);//Set the mail subject message.setText(mail_body);//Set the mail content message.setHeader(mail_head_name, mail_head_value);//Set the mail title message.setSentDate(new Date());//Set the mail sending period Address address = new InternetAddress(mail_from,personalName); message.setFrom(address);//Set the address of the sender of the mail Address toaddress = new InternetAddress(mail_to);//Set the address of the mail recipient message.addRecipient(Message.RecipientType.TO,toaddress); System.out.println(message); Transport.send(message); System.out.println("Send Mail Ok!"); } catch (Exception e) { e.printStackTrace(); } //return flag; }}Code 3. Test.java code to test the sending email
public class Test { public static void main(String[] args) { Mail m = new Mail(); try { m.sendMail(); } catch (Exception e) { } }}I hope this article will be helpful to everyone's Java programming.