javamail发邮件

来源:互联网 发布:最新2017网络热点事件 编辑:程序博客网 时间:2024/04/29 04:10

下载第三方 jar包

javamail-1.4.7



在button的click事件中加入代码:

Properties props=new Properties();props.put("mail.smtp.host", "smtp.163.com");props.put("mail.smtp.socketFactory.port", "465");props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");props.put("mail.smtp.auth","true");props.put("mail.smtp.port","465");Session session=Session.getDefaultInstance(props,new javax.mail.Authenticator(){protected javax.mail.PasswordAuthentication getPasswordAuthentication(){return new javax.mail.PasswordAuthentication("me@163.com", "password");}});try{Message message=new MimeMessage(session);message.setFrom(new InternetAddress("me@163.com"));message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("To@gmail.com"));message.setSubject("hi this is javamail");message.setText("hi javaemail");Transport.send(message);JOptionPane.showMessageDialog(null, "message sent");}catch (Exception e) {JOptionPane.showMessageDialog(null, e);}


发邮件改写:gui


导入swt包 和 安装WindowBuilder插件From eclipse 如果你用的是netbeans就不用了


在全局中声明变量

String filename1;//附件

button——》 email 

String From=text.getText();String To=text_1.getText();String Subject=text_3.getText();String Text=text_4.getText();Properties props=new Properties();props.put("mail.smtp.host", "smtp.163.com");props.put("mail.smtp.socketFactory.port", "465");props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");props.put("mail.smtp.auth","true");props.put("mail.smtp.port","465");Session session=Session.getDefaultInstance(props,new javax.mail.Authenticator(){protected javax.mail.PasswordAuthentication getPasswordAuthentication(){return new javax.mail.PasswordAuthentication("me@163.com", "password");}});try{Message message=new MimeMessage(session);message.setFrom(new InternetAddress(From));message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To));message.setSubject(Subject);//message.setText(Text);//附件发送部分MimeBodyPart meMimeBodyPart=new MimeBodyPart();meMimeBodyPart.setText(Text); //文本内容Multipart multipart=new MimeMultipart();multipart.addBodyPart(meMimeBodyPart);meMimeBodyPart=new MimeBodyPart();javax.activation.DataSource source=new FileDataSource(filename1);meMimeBodyPart.setDataHandler(new DataHandler(source));meMimeBodyPart.setFileName(text_5.getText());multipart.addBodyPart(meMimeBodyPart);message.setContent(multipart);Transport.send(message);JOptionPane.showMessageDialog(null, "message sent");}catch (Exception e) {JOptionPane.showMessageDialog(null, e);}}


button——》attact    //添加附件


JFileChooser chooser=new JFileChooser();chooser.showOpenDialog(null);File f= chooser.getSelectedFile();filename1=f.getAbsolutePath();text_2.setText(filename1);


gmail短收件情况:





原创粉丝点击