`
derek_z
  • 浏览: 17039 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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;
    }

 

分享到:
评论

相关推荐

    javax.mail-1.4.4.jar

    通过java扩展包javax.mail-1.4.4.jar实现邮件发送功能。 import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart...

    javax.mail-1.5.6-API文档-中文版.zip

    赠送jar包:javax.mail-1.5.6.jar; 赠送原API文档:javax.mail-1.5.6-javadoc.jar; 赠送源代码:javax.mail-1.5.6-sources.jar; 赠送Maven依赖信息文件:javax.mail-1.5.6.pom; 包含翻译后的API文档:javax.mail...

    jakarta.mail-1.6.7-API文档-中英对照版.zip

    赠送jar包:jakarta.mail-1.6.7.jar; 赠送原API文档:jakarta.mail-1.6.7-javadoc.jar; 赠送源代码:jakarta.mail-1.6.7-sources.jar; 赠送Maven依赖信息文件:jakarta.mail-1.6.7.pom; 包含翻译后的API文档:...

    javax.mail-1.6.2-API文档-中英对照版.zip

    赠送jar包:javax.mail-1.6.2.jar; 赠送原API文档:javax.mail-1.6.2-javadoc.jar; 赠送源代码:javax.mail-1.6.2-sources.jar; 赠送Maven依赖信息文件:javax.mail-1.6.2.pom; 包含翻译后的API文档:javax.mail...

    javax.mail-1.5.6-API文档-中英对照版.zip

    赠送jar包:javax.mail-1.5.6.jar; 赠送原API文档:javax.mail-1.5.6-javadoc.jar; 赠送源代码:javax.mail-1.5.6-sources.jar; 赠送Maven依赖信息文件:javax.mail-1.5.6.pom; 包含翻译后的API文档:javax.mail...

    jakarta.mail-1.6.7-API文档-中文版.zip

    赠送jar包:jakarta.mail-1.6.7.jar 赠送原API文档:jakarta.mail-1.6.7-javadoc.jar 赠送源代码:jakarta.mail-1.6.7-sources.jar 包含翻译后的API文档:jakarta.mail-1.6.7-javadoc-API文档-中文(简体)版.zip ...

    mail-1.5.0-b01-API文档-中文版.zip

    赠送jar包:mail-1.5.0-b01.jar; 赠送原API文档:mail-1.5.0-b01-javadoc.jar; 赠送源代码:mail-1.5.0-b01-sources.jar; 赠送Maven依赖信息文件:mail-1.5.0-b01.pom; 包含翻译后的API文档:mail-1.5.0-b01-...

    mail1.5.4版本jar包

    《Android邮件发送:mail1.5.4版本jar包详解》 在移动应用开发中,尤其是在Android平台上,发送邮件是一项常见的需求。为了实现这一功能,开发者通常会借助于各种库和框架,其中JavaMail API是一个广泛使用的解决...

    javax.mail.jar下载

    在Java编程环境中,`javax.mail.jar` 是一个非常重要的库,它提供了用于发送和接收电子邮件的API。这个库是JavaMail API的一部分,主要用于处理SMTP(简单邮件传输协议)、POP3(邮局协议版本3)和IMAP(因特网消息...

    Java mail-1.4.7 jar包

    Java Mail 是一个开源的Java库,它为Java应用程序提供了与各种邮件系统交互的能力。这个"mail-1.4.7.jar"是Java Mail的一个版本,主要用于处理电子邮件的发送和其他相关功能。版本号1.4.7表明这是一个较旧但稳定版本...

    基于Maven的javax.mail发送邮件例子程序

    基于Maven的javax.mail发送邮件例子程序 pom.xml添加依赖jar: &lt;groupId&gt;javax.mail &lt;artifactId&gt;mail ${javamail.version} &lt;/dependency&gt; &lt;javamail.version&gt;1.4.1 /* 功能:加入了参考文章中没有...

    javax.mail-1.6.2_javamailjar1.6.2_javamail-1.6.2_javax.mail_java

    `javax.mail-1.6.2_javamailjar1.6.2_javamail-1.6.2_javax.mail_java` 这个标题暗示了我们正在讨论的是 JavaMail 的 1.6.2 版本,这是一个稳定且广泛使用的版本。 JavaMail API 提供了一套标准的接口,用于与邮件...

    Mail api Mail apiMail api

    【Mail API】是一种用于发送、接收和管理电子邮件的软件接口,它允许开发人员在应用程序中集成邮件功能。Mail API使得用户无需离开应用就能处理邮件,为开发者提供了方便且高效的工具来构建邮件相关的功能,如注册...

    javax.mail-1.6.0.jar包及移入maven仓库语句

    在Java开发中,`javax.mail`库是一个非常重要的组件,主要用于处理电子邮件的发送与接收。这个库提供了丰富的API,使得开发者能够轻松地实现邮件服务的功能。`javax.mail-1.6.0.jar`是该库的一个特定版本,包含了...

    Win7启用内置Windows Mail(32+64)

    原本Vista系统拥有的Windows Mail邮件客户端,在Win7中已经被微软阉割了(其实是隐藏了起来)。如果你想恢复Windows Mail邮件客户端,该如何操作呢?方法很简单,只要将Vista中的msoe.dll文件覆盖Win7的的“&ccedil;...

    mail.jar&activation.jar

    Mail.jar 文件通常包含了JavaMail的核心组件,提供了对SMTP、POP3、IMAP等邮件协议的支持。 而activation.jar是JavaBeans Activation Framework (JAF)的一部分,它是Java平台的标准组件,用于处理和识别不同的数据...

    Mail 错误com/sun/mail/util/LineInputStream。javaee.jar 开发包

    该开发包是解决 JavaMail 发送邮件报错:java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream错误 ava.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream 使用方法: 将javaee.jar ...

    mail.jar包

    `mail.jar`是这个过程中必不可少的一个组件,尤其在处理Spring发送邮件的功能时。本文将深入探讨`mail.jar`的作用,以及它如何与Spring框架集成,帮助开发者实现邮件服务。 `mail.jar`是一个JavaMail API的实现,它...

    linux 第十二讲 mail服务器配置与管理

    Linux Mail服务器配置与管理是系统管理员必须掌握的关键技能之一,特别是在企业环境中,电子邮件通信是日常工作的核心。Sendmail是一款广泛使用的邮件传输代理软件,适用于多种Linux发行版,包括Red Hat Enterprise ...

    JavaMail发送邮件 所需activation.jar与javax.mail.jar

    在JavaMail中,`activation.jar`和`javax.mail.jar`是两个非常重要的组件,它们是JavaMail功能实现的核心依赖。 首先,`activation.jar`是JavaBeans Activation Framework (JAF)的一部分,它主要用于处理MIME类型的...

Global site tag (gtag.js) - Google Analytics