邮件收发

邮件收发 想对网上看到的一些关于邮件收发的做一个收集,以备用到时可以参考。 普通邮件发送: public static void otherSend() throws IOException { String from = "[email protected]"; String to = "[email protected]"; String title = "The first email for javaMail"; String content = "It's cool!---feedback"; //设定属性properties Properties properties = new Properties(); //协议:smtp 或 imap mailHost: properties.put("mail.smtp.host", "smtp.163.com"); //验证 properties.put("mail.smtp.auth", "true"); //设定会话session Session session = Session.getInstance(properties); //设定message MimeMessage mimeMessage = new MimeMessage(session); InternetAddress address; try { address = new InternetAddress(from);//发送人 mimeMessage.setFrom(address); InternetAddress toAddress = new InternetAddress(to); mimeMessage.setRecipient(Message.RecipientType.TO, toAddress);//发送到,可以有多个 mimeMessage.setSubject(title);//主题 mimeMessage.setText(content);//内容 mimeMessage.setSentDate(new Date());//时间 mimeMessage.saveChanges(); Transport transport = session.getTransport("smtp");//协议 transport.connect("smtp.163.com", "langren_qing", "***"); transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients()); transport.close(); System.out.println("=======send a mail from other =================="); //在本地保存一份发送的邮件 POP3 protocol doesn't support appending messages. //MethodNotSupportedException - always /*URLName urlName = new URLName("pop3","pop.163.com",110,null,"[email protected]","***"); Store store = session.getStore(urlName); store.connect(); Folder folder = store.getFolder("INBOX"); System.out.println(folder.exists()); if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] message = new Message[1]; message[0] = mimeMessage; System.out.println(message[0].getContent().toString()); folder.appendMessages(message); System.out.println("Mail was recorded successfully.");*/ } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

对于像gmail,上面的方法是发不出去的。与其他邮箱不同的是Gmail提供的POP3和SMTP是使用安全套接字层SSL的,因此常规的JavaMail程序是无法收发邮件的。代码可以参考:http://www.javayou.com/diary/497

带附件的邮件发送可以参考:http://www.cnblogs.com/wj-wangjun/archive/2008/04/08/1141685.html

接收邮件参考:http://java.e800.com.cn/articles/2008/524/1211577268074818250_1.html

你可能感兴趣的:(properties,String,session,ssl,Gmail,javamail)