java_mail收发邮件

来源:互联网 发布:网络公司财务 编辑:程序博客网 时间:2024/05/19 09:15

一、邮件简介



示例:创建一个邮件并写到磁盘

package mail;import javax.mail.*;import javax.mail.internet.*;public class SendMail2 {public static void main(String args[]){Session session = Session.getInstance(new Properties());MimeMessage  message = new MimeMessage(session);try {//设置邮件的基本信息message.setFrom(new InternetAddress("xx@sina.com"));message.setRecipient(Message.RecipientType.TO, new InternetAddress("xx@sina.com"));message.setSubject("测试");//邮件正文MimeBodyPart text = new MimeBodyPart();text.setContent("我就是我xxx","text/html;charset=UTF-8");//创建邮件附件MimeBodyPart  attach = new MimeBodyPart();DataHandler dh = new DataHandler(new FileDataSource("e:\\z_src\\images\\1.jpg"));attach.setDataHandler(dh);attach.setFileName(dh.getName());//创建容器描述 数据关系MimeMultipart mp = new MimeMultipart();mp.addBodyPart(text);mp.addBodyPart(attach);mp.setSubType("mixed");message.setContent(mp);message.saveChanges();message.writeTo( new FileOutputStream("e:\\1.eml"));} catch (Exception e) {e.printStackTrace();}}}

示例2:发送邮件

public class SendMail {public static void main(String args[]){Properties prop = new Properties();prop.setProperty("mail.smtp.host", "smtp.sohu.com");prop.setProperty("mail.transport.protocol", "smtp");prop.setProperty("mail.smtp.auth", "true");try {//1、创建SessionSession session = Session.getInstance(prop);session.setDebug(true);//2、创建TransportTransport ts = session.getTransport();//3、创建邮件Message message =  makeMessage(session);//连上邮件服务器ts.connect("smtp.sohu.com", "username", "password");//发送邮件ts.sendMessage(message, message.getAllRecipients());ts.close();} catch (MessagingException e) {e.printStackTrace();}}public static Message makeMessage(Session session) throws AddressException, MessagingException{MimeMessage  message = new MimeMessage(session);//设置邮件的基本信息message.setFrom(new InternetAddress(""));message.setRecipient(Message.RecipientType.TO, new InternetAddress(""));message.setSubject("test");message.setContent("aaa", "text/html");return message;}}



转自:传智播客

0 0
原创粉丝点击