精华内容
下载资源
问答
  • java 发邮件

    2017-06-02 13:48:24
    java 发邮件

    java web 系统,常用邮件功能,现小结如下。

    import java.util.Properties;
    
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    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;
    public class EmailUtil {
    
    	private MimeMessage mimeMsg; // MIME邮件对象
    
    	private Session session; // 邮件会话对象
    	private Properties props; // 系统属性
    	private String username = ""; // smtp认证用户名和密码
    	private String password = "";
    
    	private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
    
    	/**
    	 * 
    	 */
    	public EmailUtil(String smtp) {
    		setSmtpHost(smtp);
    		createMimeMessage();
    	}
    
    	/**
    	 * @param hostName
    	 *            String
    	 */
    	public void setSmtpHost(String hostName) {
    		if (props == null)
    			props = System.getProperties(); // 获得系统属性对象
    		props.put("mail.smtp.host", hostName); // 设置SMTP主机
    	}
    
    	/**
    	 * @return boolean
    	 */
    	public boolean createMimeMessage() {
    		try {
    			session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
    		} catch (Exception e) {
    			return false;
    		}
    		try {
    			mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
    			mp = new MimeMultipart();
    			return true;
    		} catch (Exception e) {
    			System.out.println("创建MIME邮件对象失败!" );
    			e.printStackTrace();
    			return false;
    		}
    		
    	}
    
    	/**
    	 * @param need
    	 *            boolean
    	 */
    	public void setNeedAuth(boolean need) {
    		//LogLIB.LogRun.info("设置smtp身份认证:mail.smtp.auth = " + need);
    		if (props == null)
    			props = System.getProperties();
    
    		if (need) {
    			props.put("mail.smtp.auth", "true");
    		} else {
    			props.put("mail.smtp.auth", "false");
    		}
    	}
    
    	/**
    	 * @param name
    	 *            String
    	 * @param pass
    	 *            String
    	 */
    	public void setNamePass(String name, String pass) {
    		username = name;
    		password = pass;
    	}
    
    	/**
    	 * @param mailSubject
    	 *            String
    	 * @return boolean
    	 * @throws MessagingException 
    	 */
    	public boolean setSubject(String mailSubject) throws MessagingException {
    		System.out.println("设置邮件主题!");
    		boolean flag = false;
    		try {
    			mimeMsg.setSubject(mailSubject);
    			flag = true;
    		} catch (Exception e) {
    			System.out.println("设置邮件主题发生错误!");
    			e.printStackTrace();
    			
    		}
    		return flag;
    	}
    
    	/**
    	 * @param mailBody
    	 *            String
    	 */
    	public boolean setBody(String mailBody) {
    		try {
    			BodyPart bp = new MimeBodyPart();
    			bp.setContent(
    					"<meta http-equiv=Content-Type content=text/html; charset=gb2312>"
    							+ mailBody, "text/html;charset=GB2312");
    			mp.addBodyPart(bp);
    
    			return true;
    		} catch (Exception e) {
    			System.out.println("设置邮件正文时发生错误!");
    			e.printStackTrace();
    			return false;
    		}
    	}
    
    	/**
    	 * @param name
    	 *            String
    	 * @param pass
    	 *            String
    	 * @throws MessagingException 
    	 */
    	public boolean addFileAffix(String filename) throws MessagingException {
    		System.out.println("增加邮件附件:" + filename);
    		try {
    			BodyPart bp = new MimeBodyPart();
    			FileDataSource fileds = new FileDataSource(filename);
    			bp.setDataHandler(new DataHandler(fileds));
    			bp.setFileName(fileds.getName());
    			mp.addBodyPart(bp);
    			return true;
    		} catch (Exception e) {
    			System.out.println("增加邮件附件:" + filename + "发生错误!");
    			e.printStackTrace();
    			return false;
    		}
    	}
    
    	/**
    	 * @param name
    	 *            String
    	 * @param pass
    	 *            String
    	 */
    	public boolean setFrom(String from) {
    		System.out.println("设置发信人!");
    		try {
    			
    			mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
    			return true;
    		} catch (Exception e) {
    			return false;
    		}
    	}
    
    	/**
    	 * @param name
    	 *            String
    	 * @param pass
    	 *            String
    	 */
    	public boolean setTo(String to) {
    		if (to == null)
    			return false;
    
    		try {
    			 String[] arr = to.split(",");  
    	            int receiverCount = arr.length; 
    	            if (receiverCount > 0) {  
    	                InternetAddress[] address = new InternetAddress[receiverCount];  
    	                for (int i = 0; i < receiverCount; i++) {  
    	                    address[i] = new InternetAddress(arr[i]);  
    	                }  
    	                mimeMsg.addRecipients(Message.RecipientType.TO, address); 
    	                return true;
    	            }else{
    	            	return false;
    	            }
    			
    		} catch (Exception e) {
    			return false;
    		}
    
    	}
    
    	/**
    	 * @param name
    	 *            String
    	 * @param pass
    	 *            String
    	 */
    	public boolean setCopyTo(String copyto) {
    		if (copyto == null)
    			return false;
    		try {
    			mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress
    					.parse(copyto));
    			return true;
    		} catch (Exception e) {
    			return false;
    		}
    	}
    
    	/**
    	 * @param name
    	 *            String
    	 * @param pass
    	 *            String
    	 * @throws Exception 
    	 */
    	public boolean sendout() throws Exception {
    		try {
    			mimeMsg.setContent(mp);
    			mimeMsg.saveChanges();
    			System.out.println("正在发送邮件....");
    
    			Session mailSession = Session.getInstance(props, null);
    			Transport transport = mailSession.getTransport("smtp");
    			transport.connect((String) props.get("mail.smtp.host"), username,
    					password);
    			
    			transport.sendMessage(mimeMsg, mimeMsg
    					.getRecipients(Message.RecipientType.TO));
    
    			System.out.println("发送邮件成功!");
    			transport.close();
    
    			return true;
    		} catch (Exception e) {
    			System.out.println("邮件发送失败!");
    			throw e;
    		}
    	}
    
    	/**
    	 * 发邮件
    	 * @param mailSubject
    	 * @param mailBody
    	 * @param sendToAddress
    	 * @param sendFromAddress
    	 * @param smtp
    	 * @param username
    	 * @param password
    	 * @param filename
    	 * @throws Exception 
    	 */
    	public static void toSendEmail(String mailSubject, String mailBody,
    			String sendToAddress, String sendFromAddress, String smtp,
    			String username, String password, String filename) throws Exception {
    		EmailUtil themail = new EmailUtil(smtp);
    		themail.setNeedAuth(true);
    		if (themail.setSubject(mailSubject) == false)
    			return;
    		if (themail.setBody(mailBody) == false)
    			return;
    		if (themail.setTo(sendToAddress) == false)
    			return;
    		if (themail.setFrom(sendFromAddress) == false)
    			return;
    		if (themail.addFileAffix(filename) == false)
    			return;
    		themail.setNamePass(username, password);
    		if (themail.sendout() == false)
    			return;
    	}
    	/**
    	 * 发邮件
    	 * @param mailSubject
    	 * @param mailBody
    	 * @param sendToAddress
    	 * @param sendFromAddress
    	 * @param smtp
    	 * @param username
    	 * @param password
    	 * @param filename
    	 * @throws Exception 
    	 */
    	public static void toSendEmail(String mailSubject, String mailBody,
    			String sendToAddress, String sendFromAddress, String smtp,
    			String username, String password) throws Exception {
    		EmailUtil themail = new EmailUtil(smtp);
    		themail.setNeedAuth(true);
    		if (themail.setSubject(mailSubject) == false)
    			return;
    		if (themail.setBody(mailBody) == false)
    			return;
    		if (themail.setTo(sendToAddress) == false)
    			return;
    		if (themail.setFrom(sendFromAddress) == false)
    			return;
    		themail.setNamePass(username, password);
    		if (themail.sendout() == false)
    			return;
    	}
    
    	public static void sendEmailNotFile(String receiver, String title,
    			String content) throws Exception{
    		EmailUtil.toSendEmail(title, content, receiver,
    				Constant.DEFAULT_EMAIL_ADDRESS,//系统默认邮件地址
    				Constant.DEFAULT_EMAIL_SMTP, //默认SMTP 比如 smtp.exmail.qq.com
    				Constant.DEFAULT_EMAIL_ADDRESS, //系统默认邮件地址
    				Constant.DEFAULT_EMAIL_PASSWORD //系统邮箱密码
    				);
    	}
    	
    	public static void sendEmail(String filePath, String receiver, String title,
    			String content) throws Exception {
    		EmailUtil.toSendEmail(title, content, receiver,
    				Constant.DEFAULT_EMAIL_ADDRESS,//系统默认邮件地址
    				 Constant.DEFAULT_EMAIL_SMTP,//默认SMTP 比如 smtp.exmail.qq.com
    				Constant.DEFAULT_EMAIL_ADDRESS,//系统默认邮件地址
    				Constant.DEFAULT_EMAIL_PASSWORD,//系统邮箱密码
    				filePath);
    	}
    
    	public static void main(String[] args) {
    		try {
    			EmailUtil.sendEmail("D:/test.txt","qq1@example.com,qq2@example.com", "这是一份测试邮件", "这是一份测试邮件");
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}
    		
    	}
    }


    展开全文
  • java发邮件

    2013-10-29 19:04:19
    java发邮件有兴趣可以看看、
  • Java发邮件

    2019-12-05 14:37:07
    Java发邮件 加jar包 <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.4</version> </dependency&g...

    Java发邮件

    • 加jar包
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-email</artifactId>
        <version>1.4</version>
    </dependency>
    
    • util类
    	// 发件人 账号和密码
        public static final String MY_EMAIL_ACCOUNT = "xxxx@163.com";
        public static final String MY_EMAIL_PASSWORD = "xxxxx";// 密码,是你自己的设置的授权码
    
        // SMTP服务器(这里用的163 SMTP服务器)
        public static final String MEAIL_163_SMTP_HOST = "smtp.163.com";
        public static final String SMTP_163_PORT = "25";// 端口号,这个是163使用到的;QQ的465或者875
    
        // 收件人
        public static final String RECEIVE_EMAIL_ACCOUNT = "xxxx@163.com";
    
        public static void emailUtil(){
            try{
                Properties p = new Properties();
                p.setProperty("mail.smtp.host", MEAIL_163_SMTP_HOST);
                p.setProperty("mail.smtp.port", SMTP_163_PORT);
                p.setProperty("mail.smtp.socketFactory.port", SMTP_163_PORT);
                p.setProperty("mail.smtp.auth", "true");
                p.setProperty("mail.smtp.socketFactory.class", "SSL_FACTORY");
    
                Session session = Session.getInstance(p, new Authenticator() {
                    // 设置认证账户信息
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD);
                    }
                });
                session.setDebug(true);
                System.out.println("创建邮件");
                MimeMessage message = new MimeMessage(session);
                // 发件人
                message.setFrom(new InternetAddress(MY_EMAIL_ACCOUNT));
                // 收件人和抄送人
                message.setRecipients(Message.RecipientType.TO, RECEIVE_EMAIL_ACCOUNT);
                message.setRecipients(Message.RecipientType.CC, MY_EMAIL_ACCOUNT);
    
                // 内容
                message.setSubject("验证码");
                message.setContent("<html lang='zh-CN'><head ><meta charset='utf-8'>"
                                + "</head><body>内容:早上好"
                                + "<a href='http://www.baidu.com'>【百度一下】</a></body></html>",
                        "text/html;charset=utf-8");
                message.setSentDate(new Date());
                message.saveChanges();
                System.out.println("准备发送");
                Transport.send(message);
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
        }
    
    • 调用
    public static void main(String[] args) throws AddressException, MessagingException {
    	emailUtil();
    }
    
    展开全文
  • JAVA发邮件

    2010-11-15 09:16:00
  • Java 发邮件

    2016-12-11 19:13:00
    Java 发邮件 <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> ...

     Java 发邮件

    <dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
    </dependency>

     

     

    package cn.gszhang.common.base.utils;


    import java.util.Properties;

    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    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;


    public class EmailUtis {
    private Properties props; //系统属性
    private Session session; //邮件会话对象
    private MimeMessage mimeMsg; //MIME邮件对象

    /**
    * Constructor
    * @param smtp 邮件发送服务器
    */
    public EmailUtis(String smtp, String username, String password){
    props = System.getProperties();
    props.put("mail.smtp.auth","true");
    props.put("mail.smtp.host", smtp);
    props.put("username", username);
    props.put("password", password);
    session = Session.getDefaultInstance(props, null);
    session.setDebug(true);
    mimeMsg = new MimeMessage(session);
    }


    public boolean sendMail(String from, String[] to, String[] copyto, String subject, String content, String[] fileName) {
    try {
    //设置发信人
    mimeMsg.setFrom(new InternetAddress(from));
    //设置接收人
    for (int i = 0; i < to.length; i++) {
    mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to[i]));
    }
    //设置抄送人
    for (int i = 0; i < copyto.length; i++) {
    mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copyto[i]));
    }
    //设置主题
    mimeMsg.setSubject(subject);

    if(null!=fileName){
    BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
    mdp.setContent(content, "text/html;charset=UTF-8");// 给BodyPart对象设置内容和格式/编码方式
    Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对象
    mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)

    MimeBodyPart filePart ;
    FileDataSource fileDataSource ;
    for (int j = 0; j < fileName.length; j++) {
    mdp = new MimeBodyPart();
    filePart = new MimeBodyPart();
    fileDataSource = new FileDataSource(fileName[j]);
    filePart.setDataHandler(new DataHandler(fileDataSource));
    try {
    filePart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
    } catch (Exception e) {
    e.printStackTrace();
    }
    mm.addBodyPart(filePart);
    }
    mimeMsg.setContent(mm);
    }else{
    BodyPart mdp = new MimeBodyPart();
    mdp.setContent(content, "text/html;charset=UTF-8");// 给BodyPart对象设置内容和格式/编码方式
    Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对象
    mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
    mimeMsg.setContent(mm);
    }

    //发送邮件
    if(props.get("mail.smtp.auth").equals("true")){
    Transport transport = session.getTransport("smtp");
    transport.connect((String)props.get("mail.smtp.host"), (String)props.get("username"), (String)props.get("password"));
    transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
    transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
    transport.close();
    }else{
    Transport.send(mimeMsg);
    }
    System.out.println("邮件发送成功");
    } catch (MessagingException e) {
    e.printStackTrace();
    }
    return true;
    }

     

    public static void main(String[] args) {
    String smtp = "smtp.163.com";
    String username="zhgs_cq@163.com";
    String password=""; //填写邮箱的密码
    String from = "zhgs_cq@163.com";
    String[] to = {"470417164@qq.com,973669404@qq.com"};
    String[] copyto = {"973669404@qq.com"};
    String subject = "主题";
    String content = "邮件内容";
    String[] fileName = {"D:\\WI-FI密码.txt","D:\\张高松 Java软件工程师.doc"};
    // String[] fileName = null;// {"D:\\WI-FI密码.txt"};
    EmailUtis email = new EmailUtis(smtp, username, password);
    email.sendMail(from, to, copyto, subject, content, fileName);

    }



    }

    转载于:https://www.cnblogs.com/zhanggaosong/p/6160250.html

    展开全文
  • java发邮件jar

    2017-08-17 12:49:20
    java发邮件
  • JAVA 发邮件

    2018-08-11 02:00:16
    public void sendEmail(String str) throws MessagingException { ...开始发送邮件"); JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); // 设定mail server senderImpl.setHo...
  • java发邮件程序

    2018-07-18 10:30:54
    java发邮件程序java发邮件程序java发邮件程序java发邮件程序

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,181
精华内容 1,272
关键字:

java发邮件

java 订阅