Email knowledge

1. Configure the mail session for the application

javax.mail.Session saves the configuration properties of the mail system and provides information for user authentication. To send an email, you must first obtain the session object.

(1) Session.getInstance(java.util.Properties) to obtain a non-shared session object

(2) Session.getDefaultInstance(java.utilProperties) to obtain a shared session object

    Both must establish Properties prop=new Properties() object;

note : A shared Session object is typically used for single-user desktop applications.

The mail.smtp.host (mail.protocol.host protocol-specific mail server name) property is usually set when sending Email using the SMTP protocol.

prop.put("mail.smtp.host","smtp.mailServer.com");

Session mailSession=Session.getInstance(prop);

Note: In the process of real use and creation, we are often asked to verify the password, which is We are going to write a password authentication class. javax.mail.Authenticator is an abstract class, we want to write the password authentication class of MyAuthenticator, which inherits the Authenticator implementation:

 protected PasswordAuthentication getPasswordAuthentication(){  
      return new PasswordAuthentication(String userName, String password);  
  }

At this point we create the Session object:

      Session mailSession=Session.getInstance(prop,new MyAuthenticator(userName,Password));

And to set the use of authentication: prop.put("mail. smtp.auth","true");

Use STARTTLS secure connection: prop.put("mail.smtp.starttls.enable","true");

2. After configuring the mail session, to write a message

To write a message, it is necessary to generate An instance of a subclass of javax.mail.Message or use the javax.mail.interet.MimeMessage class for Internet mail.

(1) Establish a MimeMessage object

MimeMessage extends the abstract Message class, and construct a MimeMessage object:

MimeMessage message=new MimeMessage(mailSession);

(2) Message sender, date, subject

message.setFrom(Address theSender);

message.setSentDate(java. util.Date theDate);

message.setSubject(String theSubject);

(3) Set the recipient and sender of the message (addressed reception)

     setRecipient(Message.RecipientType type , Address theAddress), setRecipients(Message.RecipientType type , Address[] theAddress), addRecipient( Message.RecipientType type , Address theAddress) and addRecipients(Message.RecipientType type,Address[] theAddress) methods can specify the recipient type, but the latter two are generally used to avoid accidental replacement or overwriting of the recipient list. Define the recipient type:

Message.RecipientType.TO: Message recipient

Message.RecipientType.CC: Message CC recipient

Message.RecipientType.BCC: Anonymous CC recipient (other recipients cannot see the recipient's name and address)

(4) Setting the message content

JavaMail is based on JavaBean Activation FrameWork (JAF). JAF can construct text messages and also support attachments.

When setting the message content, you need to provide the content type of the message----that is, the method signature:

MimeMessage.setContent(Object theContent,String type);

It is also not necessary to explicitly formulate the content type of the message: MimeMessage.setText(String theText);

Note: create an address javax.mail.InternetAddress toAddress=new InternetAddress(String address);

3. Send Email, here is an example of a text message

javax .mail.Transport class to send messages. At this time, the Transport object communicates with the corresponding transport protocol, here is the SMTP protocol.

Transport transport = mailSession.getTransport("smtp");//Define sending protocol
transport.connect(smtpHost,"chaofeng19861126", fromUserPassword);//Login mailbox
transport.send(message, message.getRecipients(RecipientType.TO)); //Send mail

Here is a complete code: --------->>SendMail.java

[java] view plain copy

    package com.tools;  
      
    import java.util.Calendar;  
    import java.util.Properties;  
      
    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.MimeMessage;  
      
    public class SendMail {  
        @SuppressWarnings("static-access")  
        public static void sendMessage(String smtpHost, String from,  
                String fromUserPassword, String to, String subject,  
                String messageText, String messageType) throws MessagingException {  
            // 第一步:配置javax.mail.Session对象  
            System.out.println("as" + smtpHost + "configure mail session object");  
              
              
            Properties props = new Properties();  
            props.put("mail.smtp.host", smtpHost); props.put  
            ("mail. smtp.starttls.enable","true");//Use STARTTLS secure connection//  
            props.put("mail.smtp.port", "25"); //google uses port 465 or 587  
            props.put(" mail.smtp.auth", "true"); // use authentication  
            //props.put("mail.debug", "true");  
            Session mailSession = Session.getInstance(props,new MyAuthenticator(from,fromUserPassword)) ;  
      
            // Step 2: Write the message  
            System.out.println("   编写消息from——to:" + from + "——" + to);  
      
            InternetAddress fromAddress = new InternetAddress(from);  
            InternetAddress toAddress = new InternetAddress(to);  
      
            MimeMessage message = new MimeMessage(mailSession);  
      
            message.setFrom(fromAddress);  
            message.addRecipient(RecipientType.TO, toAddress);  
      
            message.setSentDate(Calendar.getInstance().getTime());  
            message.setSubject(subject);  
            message.setContent(messageText, messageType);  
      
            // 第三步:发送消息  
            Transport transport = mailSession.getTransport("smtp");  
            transport.connect(smtpHost,"chaofeng19861126", fromUserPassword);  
            transport.send(message, message.getRecipients(RecipientType.TO));  
            System.out.println("message yes");  
        }  
      
        public static void main(String[] args) {  
            try {  
                SendMail.sendMessage("smtp.gmail.com", "[email protected]",  
                        "************", "[email protected]", "nihao",  
                        "---------------wrwe-----------",  
                        "text/html;charset=gb2312");  
            } catch (MessagingException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
    }  
    class MyAuthenticator extends Authenticator{  
        String userName="";  
        String password="";  
        public MyAuthenticator(){  
              
        }  
        public MyAuthenticator(String userName,String password){  
            this.userName=userName;  
            this.password=password;  
        }  
         protected PasswordAuthentication getPasswordAuthentication(){     
            return new PasswordAuthentication(userName, password);     
         }   
    } 




From: http://blog.csdn.net/karem/article/details/4646071

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325574929&siteId=291194637