Mail

package ...

import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;


public class JavaMail {


    private MimeMessage mimeMsg;
    private Session session;
    private Properties props;
    private boolean needAuth;
    private String username;
    private String password;
    private Multipart mp;
    private String sendTo;

    public JavaMail() throws Exception {
        needAuth = false;
        username = "";
        password = "";
    }

    public JavaMail(Properties prop) throws Exception {
        needAuth = false;
        username = "";
        password = "";
        props = prop;
        try {
            session = Session.getDefaultInstance(props, null);
            mimeMsg = new MimeMessage(session);
            mp = new MimeMultipart();
        }
        catch (Exception e) {
            throw new Exception("Create MIME object fails");
        }
    }

    public void setSmtpHost(String hostName) {
        if (props == null)
            props = System.getProperties();
        props.put("mail.smtp.host", hostName);
    }

    public void createMimeMessage()
            throws Exception {
        try {
            session = Session.getDefaultInstance(props, null);
            mimeMsg = new MimeMessage(session);
            mp = new MimeMultipart();
        }
        catch (Exception e) {
            throw new Exception("Create MIME object fail");
        }
    }

    public void setNeedAuth(boolean need) {
        if (props == null)
            props = System.getProperties();
        if (need)
            props.put("mail.smtp.auth", "true");
        else
            props.put("mail.smtp.auth", "false");
    }

    public void setNamePass(String name, String pass) {
        username = name;
        password = pass;
    }

    public void setSubject(String mailSubject)
            throws Exception {
        try {
            mimeMsg.setSubject(mailSubject, "GBK");
        }
        catch (Exception e) {
        	e.printStackTrace();
            throw new Exception("Set mail subject fail");
        }
    }

    public void setBody(String mailBody)
            throws Exception {
        try {
            BodyPart bp = new MimeBodyPart();
			bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=GBK>" + mailBody, "text/html;charset=GBK");
            mailBody = new String(mailBody.getBytes(), "GB2312");
            bp.setText(mailBody);

            mp.addBodyPart(bp);

        }
        catch (Exception e) {
            throw new Exception("Set boby fail");
        }
    }
    
    public void setHtmlBody(String mailBody) throws Exception{
    	try {
            BodyPart bp = new MimeBodyPart();
			bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=GBK>" + mailBody, "text/html;charset=GBK");
            mp.addBodyPart(bp);

        }
        catch (Exception e) {
            throw new Exception("Set boby fail");
        }
    }

    public void addFileAffix(String filename)
            throws Exception {
        try {
            BodyPart bp = new MimeBodyPart();
            FileDataSource fileds = new FileDataSource(filename);
            bp.setDataHandler(new DataHandler(fileds));
            bp.setFileName(fileds.getName());
            mp.addBodyPart(bp);
        }
        catch (Exception e) {
            throw new Exception("Add attachment" + filename + " fail");
        }
    }
    public void addFileAffix(String fileName,byte[] b)
		    throws Exception {
		try {
		    BodyPart bp = new MimeBodyPart();
		    bp.setDataHandler(new DataHandler(new ByteArrayDataSource( b, "application/octet-stream")));
		    bp.setFileName(fileName );
		    mp.addBodyPart(bp);
		}
		catch (Exception e) {
		    throw new Exception("Add attachment fail");
		}
	}

    public void setFrom(String from)
            throws Exception {
        try {
            mimeMsg.setFrom(new InternetAddress(from));
        }
        catch (Exception e) {
            throw new Exception("Set from fail");
        }
    }

    public void setTo(String to)
            throws Exception {
        if (to == null)
            return;
        try {
            this.sendTo = to;
            mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
        }
        catch (Exception e) {
            throw new Exception("Set RecipientType.TO fail");
        }
    }

    public String getTo() {
        return this.sendTo;
    }

    public void setCc(String cc)
            throws Exception {
        if (cc == null)
            return;
        try {
            mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(cc));
        }
        catch (Exception e) {
            throw new Exception("Set RecipientType.CC fail");
        }
    }

    public void sendout()
            throws Exception {
        try {
           // System.out.println("sendout--->1111111111");
            mimeMsg.setContent(mp);
           // System.out.println("sendout--->2222222222");
            mimeMsg.saveChanges();
           // System.out.println("sendout--->3333333333");
            Session mailSession = Session.getInstance(props, null);
           // System.out.println("sendout--->444444444");
            Transport transport = mailSession.getTransport("smtp");
           // System.out.println("sendout--->5555555555");
            transport.connect((String) props.get("mail.smtp.host"), username, password);
            //System.out.println("sendout--->66666666666");
            transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
           // System.out.println("sendout--->7777777777");
            transport.close();
            //System.out.println("sendout--->888888888");
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println("sendout--->error info"+e.toString());
            //throw new MailException("Send mail fail");
        }
    }

}

 

package ....;



import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;


public class SendMailUtils {
    public static JavaMail generateMail(Map<String,Object> paraMap) throws Exception {
        String subject = (String) paraMap.get("subject");
        String subjectTemp = (String) paraMap.get("subjectTemp");
        Object[] subject_ = (Object[]) paraMap.get("subject_");
        String content = (String) paraMap.get("content");
        String contentTemp = (String) paraMap.get("contentTemp");
        Object[] content_ = (Object[]) paraMap.get("content_");
        String mailSuffix = "@" + Common.MAIL_SUFFIX;
        String mailFrom = Common.MAIL_SENDER;
        String mailTo = paraMap.get("sendto") + mailSuffix;
        String userName = Common.MAIL_USER;
        String password = Common.MAIL_PASSWORD;

        JavaMail mail = null;

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", Common.MAIL_SMTP_HOST);
    		props.setProperty("mail.smtp.connectiontimeout", "5000");
			props.setProperty("mail.smtp.timeout", "5000");
            mail = new JavaMail(props);
        } catch (Exception e) {
            throw new Exception(e);
        }

//        if ((subject == null) || (subject.length() == 0)) {
//            subject = MessageFormat.format(getString(subjectTemp), subject_);
//        }
//
//        if ((content == null) || (content.length() == 0)) {
//            content = MessageFormat.format(getString(contentTemp), content_);
//        }

        try {
            mail.setFrom(mailFrom);
            mail.setTo(mailTo);
            mail.setNeedAuth(true);
            mail.setNamePass(userName, password);
            mail.setSubject(subject);
            mail.setBody(content);
        } catch (Exception e) {
            throw new Exception(e);
        }

        return mail;
    }

//    public static String getString(String key) {
//        return ResourceBundle.getBundle("iframe-default").getString(key);
//    }

    public static void sendMail(List<JavaMail> mailList) throws Exception {
        if (mailList == null) {
            return;
        }

        Iterator<JavaMail> mailIterator = mailList.iterator();
        try {
            while (mailIterator.hasNext()) {
                JavaMail mail = (JavaMail) mailIterator.next();
                mail.sendout();
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
}

 

  public static String sendEmail(Map<String,String> map) throws Exception{
    	java.util.List<JavaMail> emails = new ArrayList<JavaMail>();
    	String code = "0";
    	String _email = (String)map.get("email");
    	String title = (String)map.get("title");
    	String content = (String)map.get("content");
    	
    	try {
    		String[] _emails = _email.split(",");
    		if (_emails != null && _emails.length > 0) {
//    			String mailSuffix = "@" + SendMailUtils.getString("mail.suffix");
    			String mailFrom = Common.MAIL_SENDER;
    			String userName = Common.MAIL_USER;
    			String password = Common.MAIL_PASSWORD;
    			
    			for (int i = 0; i < _emails.length; i++) {
    				if (StringUtils.isNotBlank(_emails[i])) {
    					String mailTo = _emails[i];// + mailSuffix;
    					JavaMail mail = null;
						Properties props = new Properties();
						props.put("mail.smtp.host", Common.MAIL_SMTP_HOST);
						mail = new JavaMail(props);
						mail.setFrom(mailFrom);
						mail.setTo(mailTo);
						mail.setNeedAuth(true);
						mail.setNamePass(userName, password);
						mail.addFileAffix("文件名称",new byte[1]);// 待附件,加入文件的byte流即可
						mail.setSubject(title);
						mail.setHtmlBody(StringUtils.isNotBlank(content)?content:"");
						emails.add(mail);
    				}
    			}
    			
    			SendMailUtils.sendMail(emails);
    		}
    		code = "1";
		} catch (Exception e) {
			e.printStackTrace();
		}
        return code;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值