JAVA controlled mail sending

package sliver.utils;
import java.util.Date; 
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 
import javax.mail.internet.MimeUtility; 
import javax.mail.internet.InternetAddress; 
/**
* Mail class
* @author cjy
* */
public class Mail {
String to = ""; // recipient  [email protected]
    String from = ""; // Sender: [email protected]
    String host = ""; // smtp host such as 163: smtp.163.com
    String username = ""; // sender's username 
    String password = ""; // send The letter's password 
    String subject = ""; // Mail subject 
    String content = ""; // Mail body
    // The file name of the mail attachment     
    private String[] fileNames; 
   
    public Mail() { 
    } 
 
    public Mail(String to, String from , String host, String username, 
            String password, String subject, String content,String[] fileNames) { 
        this.to = to; 
        this.from = from; 
        this.host = host; 
        this.username = username; 
        this.password = password; 
        this.subject = subject; 
        this.content = content; 
        this.fileNames = fileNames; 
    } 
 
    /**
     * 把主题转换为中文  
     * @param strText
     * @return String
     */ 
    public String transferChinese(String strText) { 
 
        try { 
            strText = MimeUtility.encodeText(new String(strText.getBytes(), 
                    "UTF-8"), "UTF-8", "B"); //GB2312
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
 
        return strText; 
    } 
 
    /**
     * Send mail
     * 
     * @return success Returns true, returns false on failure
     */ 
    public boolean toSend() { 
        // Construct mail session 
        Properties props = System.getProperties(); 
        props.put("mail.smtp.host", host); //Specify the connected mail server Hostname
        props.put("mail.smtp.auth", "true"); //Specify whether the client wants the mail server to submit authentication
        Session session = Session.getDefaultInstance(props, 
                new Authenticator() { 
                    public PasswordAuthentication getPasswordAuthentication() { 
                        return new PasswordAuthentication(username, password); 
                    } 
                }); 
       /* The Authenticator class is an abstract class, and the Authenticator object passed to the getInstance method can only be an instance object of its subclass.
        The return value of Authenticator to the defined method is null,
                so its subclasses must override this method, which is implemented by the mail developer. */
        try { 
            // Construct MimeMessage and set basic values, create message object 
            MimeMessage msg = new MimeMessage(session); 
            // Set message content 
            msg.setFrom(new InternetAddress(from)); 
            System.out.println(from ); 
            // Map email addresses to Internet addresses 
            InternetAddress[] address = { new InternetAddress(to) }; 
            /**
             * setRecipient(Message.RecipientType type, Address
             * address), which is used to set the recipient of the mail. <br>
             * There are two parameters, the first parameter is the type of the receiver, and the second parameter is the receiver. <br>
             * The recipient type can be Message.RecipientType.TO, Message
             *.RecipientType.CC and Message.RecipientType.BCC, TO means primary recipient, CC means CC
             *, BCC means Bcc. Receivers, like senders, usually use the InternetAddress object.
             */ 
            msg.setRecipients(Message.RecipientType.TO, address); 
            // Set the subject of the message 
            subject = transferChinese(subject); 
            msg.setSubject(subject); 
            // Construct a Multipart 
            Multipart mp = new MimeMultipart(); 
 
            // Add body 
            MimeBodyPart to Multipart mbpContent = new MimeBodyPart(); 
            // Set the content of the mail (plain text format) 
            // mbpContent.setText(content); 
            // Set the content of the mail (HTML format) 
            mbpContent.setContent(content, "text/html;charset=utf-8"); 
            //Add to MimeMessage (Multipart represents the body) 
            mp.addBodyPart(mbpContent); 
            //Attachment
            if(fileNames!=null && fileNames.length> 0){
            for(int i=0;i<fileNames.length;i++){
            if(!Utils.isEmpty(fileNames[i])){
            BodyPart fileContent = new MimeBodyPart(); 
                        DataSource source = new FileDataSource(fileNames[i]);
                        fileContent.setDataHandler(new DataHandler(source));
                        String fileName=fileNames[i].substring(fileNames[i].lastIndexOf("\\")+1,fileNames[i].length());
                        fileContent.setFileName(MimeUtility.encodeText(fileName,"UTF-8",null));
                        mp.addBodyPart(fileContent); 
            }
               }
            }
            msg.setContent(mp); 
            msg.setSentDate(new Date()); 
            Transport.send(msg); 
        } catch (Exception e) { 
            e.printStackTrace(); 
            return false; 
        } 
        return true; 
    } 
 
  
    /**
* Send mail
*
* @param toMail
* recipient address
* @param fromMail
* sender address, that is, sender's username
* @param fromMailPassWord
* sender's email password
* @param subject email subject
* @param content email content
* @return boolean send success or not, true success
* */
public static boolean sendMail(String toMail, String fromMail,
String fromMailPassWord, String subject, String content,String[] fileNames) {
// create mail
Mail mail = new Mail();
mail.setTo(toMail);
mail.setFrom(fromMail);// your mailbox
String host="hwimap.exmail.qq.com";
mail.setHost(host);// sender's email host "smtp.sina.com"
mail.setUsername(fromMail);// sender user
mail.setPassword( fromMailPassWord);// sender password
mail.setSubject(subject);
mail.setContent(content);
mail.setFileNames(fileNames);
boolean send=mail.toSend();
if (send) {
System.out.println( "Your application has been submitted successfully, please check your mailbox:" + toMail);
} else {
System.out.println("The operation failed, please try again later!");
}
return send;
}
public static void main( String[] args) {
String[] str={"C:\\Program Files\\Dishes.txt","C:\\Program Files\\Alipay Scanning Invoicing Solution-Version 2.0.pdf"};
Mail.sendMail("[email protected]", "[email protected]", "Winbox473JY", "徐远方", "请到二楼办公室!",str);
}


public String getTo() { 
        return to; 
    } 
 
    public void setTo(String to) { 
        this.to = to; 
    } 
 
    public String getFrom() { 
        return from; 
    } 
 
    public void setFrom(String from) { 
        this.from = from; 
    } 
 
    public String getHost() { 
        return host; 
    } 
 
    public void setHost(String host) { 
        this.host = host; 
    } 
 
    public String getUsername() { 
        return username; 
    } 
 
    public void setUsername(String username) { 
        this.username = username; 
    } 
 
    public String getPassword() { 
        return password; 
    } 
 
    public void setPassword(String password) { 
        this.password = password; 
    } 
 
    public String getSubject() { 
        return subject; 
    } 
 
    public void setSubject(String subject) { 
        this.subject = subject; 
    } 
 
    public String getContent() { 
        return content; 
    } 
 
    public void setContent(String content) { 
        this.content = content; 
    }

public String[] getFileNames() {
return fileNames;
}

public void setFileNames(String[] fileNames) {
this.fileNames = fileNames;
}
   
   
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326716839&siteId=291194637