java mail sending, support for multiple recipients, attachments

     Don't say much, just go to the code (the test passed)

    

package test.com;

import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.*;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
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 javax.mail.internet.MimeUtility;

/**
 * <p>
 * Title: Send mail using javamail
 * </p>
 */
@SuppressWarnings("rawtypes")
public class MailUtils {
	String to = ""; // recipient
	String from = ""; // sender
	String host = ""; // smtp host
	String username = "";
	String password = "";
	String filename = ""; // attachment filename
	String subject = ""; // email subject
	String content = ""; // message body
	Vector file = new Vector(); // collection of attachment files

	/**
	 * <br>
	 * Method description: default constructor<br>
	 * Input parameters: <br>
	 * Return type:
	 */
	public MailUtils () {

	}

	/**
	 * <br>
	 * Method description: Constructor, providing direct parameters to pass in <br>
	 * Input parameters: <br>
	 * Return type:
	 */
	public MailUtils(String to, String from, String smtpServer, String username, String password, String subject,
			String content) {
		this.to = to;
		this.from = from;
		this.host = smtpServer;
		this.username = username;
		this.password = password;
		this.subject = subject;
		this.content = content;
	}

	/**
	 * <br>
	 * Method description: Set the mail server address<br>
	 * Input parameter: String host mail server address name<br>
	 * Return type:
	 */
	public void setHost(String host) {
		this.host = host;
	}

	/**
	 * <br>
	 * Method description: Set the login server verification password<br>
	 * Input parameters: <br>
	 * Return type:
	 */
	public void setPassWord(String pwd) {
		this.password = pwd;
	}

	/**
	 * <br>
	 * Method description: Set the login server to verify the user<br>
	 * Input parameters: <br>
	 * Return type:
	 */
	public void setUserName(String usn) {
		this.username = usn;
	}

	/**
	 * <br>
	 * Method description: Set the email destination mailbox<br>
	 * Input parameters: <br>
	 * Return type:
	 */
	public void setTo(String to) {
		this.to = to;
	}

	/**
	 * <br>
	 * Method description: Set the email source mailbox<br>
	 * Input parameters: <br>
	 * Return type:
	 */
	public void setFrom(String from) {
		this.from = from;
	}

	/**
	 * <br>
	 * How to: Set the subject of the email<br>
	 * Input parameters: <br>
	 * Return type:
	 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

	/**
	 * <br>
	 * Method description: Set the content of the mail<br>
	 * Input parameters: <br>
	 * Return type:
	 */
	public void setContent(String content) {
		this.content = content;
	}

	/**
	 * <br>
	 * Instructions: Convert the theme to Chinese<br>
	 * Input parameter: String strText <br>
	 * Return type:
	 */
	public String transferChinese(String strText) {
		try {
			strText = MimeUtility.encodeText(new String(strText.getBytes(), "GB2312"), "GB2312", "B");
		} catch (Exception e) {
			e.printStackTrace ();
		}
		return strText;
	}

	/**
	 * <br>
	 * Instructions: Add attachments to the attachment combination<br>
	 * Input parameters: <br>
	 * Return type:
	 */
	@SuppressWarnings("unchecked")
	public void attachfile(String fname) {
		file.addElement(fname);
	}

	/**
	 * <br>
	 * Method description: send mail<br>
	 * Input parameters: <br>
	 * Return type: boolean success is true, otherwise false
	 */
	public boolean sendMail() {

		// Construct mail session
		Properties props = new Properties();
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.auth", "true");
		Session session = Session.getDefaultInstance(props, new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		try {
			// Construct MimeMessage and set basic value
			MimeMessage msg = new MimeMessage(session);
			// MimeMessage msg = new MimeMessage();
			msg.setFrom(new InternetAddress(from));

			// msg.addRecipients(Message.RecipientType.TO, address);
			// //This can only be used to send an email to one person
			msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to));
			subject = transferChinese(subject);
			msg.setSubject(subject);

			// Construct Multipart
			Multipart mp = new MimeMultipart();

			// Add text to Multipart
			MimeBodyPart mbpContent = new MimeBodyPart();
			mbpContent.setContent(content, "text/html;charset=gb2312");

			// Add to MimeMessage (Multipart for body)
			mp.addBodyPart(mbpContent);

			// Add attachment to Multipart
			Enumeration efile = file.elements();
			while (efile.hasMoreElements()) {

				MimeBodyPart mbpFile = new MimeBodyPart();
				filename = efile.nextElement().toString();
				FileDataSource fds = new FileDataSource(filename);
				mbpFile.setDataHandler(new DataHandler(fds));
				// This method can solve the problem of garbled attachments.
				String filename = new String(fds.getName().getBytes(), "ISO-8859-1");

				mbpFile.setFileName(filename);
				// Add to MimeMessage (Multipart for attachment)
				mp.addBodyPart(mbpFile);

			}

			file.removeAllElements();
			// Add MimeMessage to Multipart
			msg.setContent(mp);
			msg.setSentDate (new Date ());
			msg.saveChanges();
			// send email
			Transport transport = session.getTransport("smtp");
			transport.connect(host, username, password);
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
		} catch (Exception mex) {
			mex.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * <br>
	 * Method description: main method, used for testing<br>
	 * Input parameters: <br>
	 * Return type:
	 */
	public static void main(String[] args) {
		MailUtils sendmail = new MailUtils ();
		// mail server address
		sendmail.setHost("smtp.qiye.163.com");
		// Mail server registered mailbox
		sendmail.setUserName("[email protected]");
		// email Password
		sendmail.setPassWord("XXXXXX");
		// recipient list
		sendmail.setTo("[email protected],[email protected],[email protected]");
		// sender email
		sendmail.setFrom("[email protected]");
		// mail title
		sendmail.setSubject("Hello, this is a test!");
		// content of email
		sendmail.setContent("Hello this is a test with multiple attachments!");

		sendmail.attachfile("d:\\2.png");
		sendmail.attachfile("d:\\2.png");

		System.out.println(sendmail.sendMail());
	}
}

 

Guess you like

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