在实际的工作开中,有时候肯定是有发送邮件的需求,所有先练习了下,这里使用的commos-emai组件和Java mail的jar包来实现的。顺便将这个应用写成Java swing程序,就算是复习swing开发了,小工具只能支持最简单的邮件发送,目前还不能上传附件。以后会跟进!
这部分就是发送邮件的核心方法,还是很easy的
public void sendMail(String hostName,String emailAddress,String password,String addTo,String addBcc,String addCc,String subject,String msg,String showName,boolean ischeck) throws EmailException{ SimpleEmail email = new SimpleEmail(); email.setTLS(ischeck); email.setHostName(hostName);//邮件服务器 email.setAuthentication(emailAddress, password);//smtp认证的用户名和密码 email.addTo(addTo); if(addCc != null && !"".equals(addCc)){ email.addBcc(addCc); } if(addBcc != null && !"".equals(addBcc)){ email.addBcc(addBcc);//密送者 } if(showName !=null && !"".equals(showName)){ email.setFrom(emailAddress, showName);//发信者 }else{ email.setFrom(emailAddress);//发信者 } email.setSubject(subject); email.setCharset("UTF-8");//编码格式 email.setMsg(msg); email.send(); }
下面就是swing的东西了,主要是书写繁琐。难道不大,展示部分代码
public void showFrame(){ //实现中心显示 Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); int x = ((int)d.width - 400) / 2; int y = ((int)d.height - 450) / 2; this.setBounds(x, y, 400, 450); this.setTitle("邮件发送客户端"); this.setVisible(true); this.setResizable(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); }
/** * 验证操作 * @return Boolean */ private Boolean check() { boolean flag = true; emailaddress = this.emailText.getText(); addto = this.addtoText.getText(); password = new String(this.passwordField.getPassword()); subject = this.subjectText.getText(); msg = this.textAreaMsg.getText(); if(emailaddress == null || "".equals(emailaddress)){ JOptionPane.showMessageDialog(this, "Email地址不能为空"); flag = false; }else if(password == null || "".equals(password)){ JOptionPane.showMessageDialog(this, "密码不能为空"); flag = false; }else if(addto == null || "".equals(addto)){ JOptionPane.showMessageDialog(this, "收件人邮箱不能为空"); flag = false; }else if(subject == null || "".equals(subject)){ JOptionPane.showMessageDialog(this, "主题不能为空"); flag = false; }else if(msg == null || "".equals(msg)){ JOptionPane.showMessageDialog(this, "邮件内容不能为空"); flag = false; }else{ flag = true; } return flag; }
if(e.getActionCommand().equals("发送")){ if(check()){ SendMail sendMail = new SendMail(); try { sendMail.sendMail(hostName, emailaddress, password, addto, addBcc, addCc, subject, msg, showName, ischeck); JOptionPane.showMessageDialog(this, "邮件发送成功!"); } catch (EmailException e1) { JOptionPane.showMessageDialog(this, "邮件发送失败!"+ e1.getMessage()); } } }
ok,主要就这么多了,工程在附件里