java mail
public class Mail {private final String SSL_FACTORY="javax.net.ssl.SSLSocketFactory";private String host = null;//服务器private int port = 25;//端口private String auth = null;//权限private String username = null;//用户邮箱private String password = null;//密码private boolean mailusername = false;//是否显示个人名称private Session session = null;//会话/** * 线程池 */ThreadPoolExecutor executor = null;{executor = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));}/** * 此方法描述的是:初始化邮件服务 * @param mails */@SuppressWarnings("unchecked")public Mail(Map<String,String> mails) {this.host = mails.get("server");//服务器int tempPort = Common.toDigit(mails.get("port"));//端口if(tempPort > 0){this.port = tempPort;}this.auth = mails.get("auth");//权限this.username=mails.get("auth_username");//权限名this.password=mails.get("auth_password");//权限密码if("1".equals(mails.get("mailusername"))){this.mailusername = true;}}/** * 此方法描述的是:初始化邮件服务 * @param host服务器 * @param port端口 * @param auth权限 * @param username用户名 * @param password密码 * @param mailusername是否显示个人名称 */public Mail(String host, int port, String auth, String username, String password, String mailusername) {this.host = host;if(port > 0){this.port=port;}this.auth = auth;this.username = username;this.password = password;if("1".equals(mailusername)){this.mailusername = true;}}/** * 此方法描述的是:创建会话 */private synchronized void createSession() {Properties mailProps = new Properties();mailProps.setProperty("mail.transport.protocol", "smtp"); //协议mailProps.setProperty("mail.smtp.host",host);//主机mailProps.setProperty("mail.smtp.port", String.valueOf(port));//端口if("smtp.gmail.com".equals(host)){mailProps.setProperty("mail.smtp.socketFactory.class",SSL_FACTORY);mailProps.setProperty("mail.smtp.socketFactory.fallback","false");mailProps.setProperty("mail.smtp.socketFactory.port",String.valueOf(port));}if ("1".equals(auth)) {//权限mailProps.put("mail.smtp.auth", "true");}//--默认初始化session = Session.getDefaultInstance(mailProps, new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(username, password);}});}/** * 此方法描述的是:创建 MimeMessage * @return */private MimeMessage createMimeMessage() {if (session == null) {createSession();}return new MimeMessage(session);}/** * 此方法描述的是:发送邮件 * @param from发送邮件 * @param toEmail目标邮件 * @param subject标题 * @param textBody内容 * @param htmlBodyhtml * @return */public String sendMessage(String from, String toEmail, String subject, String textBody, String htmlBody) {String result = null;try {String encoding = MimeUtility.mimeCharset(JspRunConfig.CHARSET); //编码MimeMessage message = createMimeMessage(); //创建信息String toEmails[] = toEmail.split(","); //目标邮件组Address to[] = new Address; //地址长度for (int i = 0; i<toEmails.length; i++) {String sTo = toEmails;if(sTo.matches("^.*<.*>$")){int index = sTo.indexOf("<");to = new InternetAddress(sTo.substring(index+1,sTo.length()-1), mailusername?sTo.substring(0, index):"", encoding);}else{to = new InternetAddress(sTo, "", encoding);}}String fromName = null;String fromEmail;if(from.matches("^.*<.*>$")){int index = from.indexOf("<");if(mailusername){fromName = from.substring(0, index);}fromEmail = from.substring(index+1,from.length()-1);}else{fromEmail = from;}Address fromAddress = new InternetAddress(fromEmail,fromName!=null?fromName:"", encoding);message.setHeader("Date", Common.gmdate("EEE, dd MMM yyyy HH:mm:ss Z", (int)(System.currentTimeMillis()/1000), "0"));message.setHeader("Content-Transfer-Encoding", "8bit");message.setRecipients(Message.RecipientType.TO, to);message.setFrom(fromAddress);message.setSubject(subject, encoding);MimeMultipart content = new MimeMultipart("alternative");if (textBody != null && htmlBody != null) {MimeBodyPart text = new MimeBodyPart();text.setText(textBody, encoding);text.setDisposition(Part.INLINE);content.addBodyPart(text);MimeBodyPart html = new MimeBodyPart();html.setContent(htmlBody, "text/html; charset="+encoding);html.setDisposition(Part.INLINE);content.addBodyPart(html);} else if (textBody != null) {MimeBodyPart text = new MimeBodyPart();text.setText(textBody, encoding);text.setDisposition(Part.INLINE);content.addBodyPart(text);} else if (htmlBody != null) {MimeBodyPart html = new MimeBodyPart();html.setContent(htmlBody, "text/html; charset="+encoding);html.setDisposition(Part.INLINE);content.addBodyPart(html);}message.setContent(content);message.setDisposition(Part.INLINE);addToTask(message);} catch (Exception e) {result=e.getMessage();}return result;}/** * 此方法描述的是:添加线程 * @param message */private void addToTask(MimeMessage message) {if (message != null) {sendMessages(Collections.singletonList(message));} else {System.out.println("Cannot add null email message to queue.");}}/** * 此方法描述的是:发送邮件 * @param messages */private void sendMessages(Collection<MimeMessage> messages) {if (messages.size() == 0) {return;}executor.execute(new EmailTask(messages));}/** * 此文件描述的是:多线程邮件发送 * @author blaiu * */private class EmailTask implements Runnable {private Collection<MimeMessage> messages;public EmailTask(Collection<MimeMessage> messages) {this.messages = messages;}public void run() {try {sendMessages();} catch (MessagingException me) {me.printStackTrace();int timestamp =(int)(System.currentTimeMillis()/1000);Log.writelog("errorlog", timestamp, timestamp+"\tSMTP\t\t("+host+":"+port+") CONNECT - Unable to connect to the SMTP server");}}public boolean sendMessages() throws MessagingException {Transport transport = null;try {URLName url = new URLName("smtp", host, port, "", username, password);transport = new SMTPTransport(session, url);transport.connect(host, port, username, password);for (MimeMessage message : messages) {transport.sendMessage(message, message.getRecipients(MimeMessage.RecipientType.TO));}return true;} finally {if (transport != null) {transport.close();}}}}}
页:
[1]