初学java javamail总结

1.配置好邮箱pop3协议,imap协议等等,腾讯邮箱记得开启这些服务,在设置---账号里面

2.导入包,或者maven导入

<!-- JavaMail -->
	<dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.7</version>
      </dependency>
	</dependencies>

3.测试小例子(借鉴别人的例子,然后我自己加以改进,可以读取邮件,把附件下载到本地)


package test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SimpleSendReceiveMessage {

	//邮件通信会话
	Session session;
	//邮件接收处理对象
	Store store;
	
	//连接邮件发送的账号与密码
	String username="自己邮箱";
	private String passwd="qq邮箱配置完pop3服务后,会给你一串东西,写这里";

	private String receiveHost="imap.qq.com";
	private String sendHost="smtp.qq.com";
	
	/**
	 * 邮件配置参数和连接接收邮件服务器
	 * @throws MessagingException
	 */
	private void init() throws MessagingException{
		Properties properties=new Properties();
		//设置发送和接收协议
		properties.put("mail.transport.protocal", "smtp");
		properties.put("mail.store.protocal", "imap");
		//设置ssl的端口
		properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		properties.setProperty("mail.imap.socketFactory.fallback", "false");
		properties.setProperty("mail.imap.port", "993");
		properties.setProperty("mail.imap.socketFactory.port", "993");
		properties.put("mail.imap.port", "993");
		properties.put("mail.smtp.port", "465");
		//smtp认证
		properties.put("mail.smtp.auth", "true");
		//设置发送和接收处理类
		properties.put("mail.transport.class", "com.sun.mail.smtp.SMTPTransport");
		properties.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");
		//设置发送邮件服务器
		properties.put("mail.smtp.host",sendHost);
		properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		//获取邮件通信会话
		Authenticator auth=new MailAuthenticator();
		session=Session.getDefaultInstance(properties,auth);
		session.setDebug(true);
		//获取接收邮件对象
		store=session.getStore("imap");
		//连接接收邮件服务器
		store.connect(receiveHost, null, null);
	}
	
	/**
	 * 关闭邮件接收服务器
	 * @throws MessagingException
	 * @throws IOException 
	 */
	public void close() throws MessagingException, IOException
	{
		store.close();
		
	}
	
	/**
	 * 创建一封简单的邮件
	 * @param fromAddr
	 * @param toAddr
	 * @return
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public Message createSimpleMessage(String fromAddr,String toAddr) throws AddressException, MessagingException{
		//建立一封邮件
		MimeMessage message=new MimeMessage(session);
		//设置发送者和接收者
		message.setFrom(new InternetAddress(fromAddr));
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
		//设置主题
		message.setSubject("使用JAVAMAIL发送邮件");
		//设置日期
		message.setSentDate(new Date(System.currentTimeMillis()));
		//设置正文
		message.setText("今天是2015-6-12,离职一个周,准备下一份工作");
		return message;
	}
	
	public Message createComplexMessage(String fromAddr,String toAddr) throws AddressException, MessagingException{
		//建立一封邮件
		MimeMessage message=new MimeMessage(session);
		//设置发送者和接收者
		message.setFrom(new InternetAddress(fromAddr));
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
		//设置主题
		message.setSubject("使用JAVAMAIL发送邮件");
		//设置日期
		message.setSentDate(new Date(System.currentTimeMillis()));
		//设置正文
		Multipart mp=createMultiPart();
		message.setContent(mp);
		return message;
	}
	
	/**
	 * 创建复杂的正文
	 * @return
	 * @throws MessagingException 
	 */
	private Multipart createMultiPart() throws MessagingException {
		// TODO Auto-generated method stub
		Multipart multipart=new MimeMultipart();
		
		//第一块
		BodyPart bodyPart1=new MimeBodyPart();
		bodyPart1.setText("创建复杂的邮件,此为正文部分");
		multipart.addBodyPart(bodyPart1);
		
		//第二块 以附件形式存在
		MimeBodyPart bodyPart2=new MimeBodyPart();
		//设置附件的处理器
		try{
			FileDataSource attachFile=new FileDataSource("D:/a.txt");
			DataHandler dh=new DataHandler(attachFile);
			bodyPart2.setDataHandler(dh);
			bodyPart2.setDisposition(Part.ATTACHMENT);
			bodyPart2.setFileName("a.txt");
			multipart.addBodyPart(bodyPart2);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		return multipart;
	}

	/**
	 * 发送邮件
	 * @param message
	 * @throws MessagingException
	 */
	public void send(Message message) throws MessagingException{
		Transport.send(message);
	}
	
	/**
	 * 接收邮件
	 * @throws Exception 
	 */
	public void receive() throws Exception{
		browseMessageFromFolder("INBOX");
	}

	/**
	 * 根据邮件夹名称浏览邮件
	 * @param folderName
	 * @throws Exception
	 */
	private void browseMessageFromFolder(String folderName) throws Exception {
		// TODO Auto-generated method stub
		Folder folder=store.getFolder(folderName);
		if(folder==null) throw new Exception(folderName+"邮件夹不存在");
		browseMessageFromFolder(folder);
	}

	/**
	 * 根据邮件夹对象浏览邮件
	 * @param folder
	 * @throws MessagingException 
	 * @throws IOException 
	 */
	private void browseMessageFromFolder(Folder folder) throws MessagingException, IOException {
		// TODO Auto-generated method stub
		folder.open(Folder.READ_ONLY);
		System.out.println("总共有"+folder.getMessageCount()+"封邮件");
		System.out.println("总共有"+folder.getUnreadMessageCount()+"封未读邮件");
		Message[] messages=folder.getMessages();
		for (int i = 1; i <=messages.length; i++) {
			System.out.println("这是第"+i+"封邮件");
			getMessageHeader(folder.getMessage(i));
			writeSubjectToOutPutStream(folder.getMessage(i));;
		}
		folder.close(false);
	}
	
	/**
	 * 遍历每封邮件的头部部分
	 * @param message
	 * @throws MessagingException 
	 */
	private void getMessageHeader(Message message) throws MessagingException {
		// TODO Auto-generated method stub
		@SuppressWarnings("unchecked")
		Enumeration<Header> allHeader=message.getAllHeaders();
		for(;allHeader.hasMoreElements();){
			Header header=allHeader.nextElement();
			System.out.println("头部信息:"+header.getName()+":"+header.getValue());
		}
	}

	/**
	 * 将每封邮件的主题写入输出流中
	 * @param message
	 * @throws MessagingException 
	 * @throws IOException 
	 */
	private void writeSubjectToOutPutStream(Message message) throws MessagingException, IOException {
		// TODO Auto-generated method stub
		System.out.println("邮件主题为:"+message.getSubject());
		System.out.println("邮件正文为:"+message.getContent().toString());
		System.out.println(message.isMimeType("multipart/*"));
		//判断是否带附件
		if(message.isMimeType("multipart/*")){
		//获取邮件中的多媒体
		Multipart multipart = (Multipart)message.getContent();
		 //循环遍历多媒体,并获取邮件体各部分
		 for (int i=0, n=multipart.getCount(); i<n; i++) {
		 Part part = multipart.getBodyPart(i);
		 //获得邮件体的部署类型
		 String disposition = part.getDisposition();
		 if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))){
		 File file=new File("D:/"+part.getFileName());
			OutputStream out=new FileOutputStream(file);
			InputStream inputstream=part.getInputStream();
			
			BufferedInputStream bufferInputStream=new BufferedInputStream(inputstream);
			BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(out);
			int m;
			while((m=bufferInputStream.read())!=-1){
				bufferedOutputStream.write(m);
				bufferedOutputStream.flush();
			}
			bufferedOutputStream.close();
		 }else if (disposition == null) {
		 MimeBodyPart mbp = (MimeBodyPart)part;
		 if (mbp.isMimeType("text/plain")) {
		 //解析过程
		 } else {
		 //其他解析过程
		  }
		 }
		 }
	}
}
	public static void main(String[] args){
		SimpleSendReceiveMessage sendReceiveMessage=new SimpleSendReceiveMessage();
		try {
			sendReceiveMessage.init();
			Message message=sendReceiveMessage.createSimpleMessage(sendReceiveMessage.username, sendReceiveMessage.username);
			//sendReceiveMessage.send(message);
			message=sendReceiveMessage.createComplexMessage(sendReceiveMessage.username, sendReceiveMessage.username);
			//sendReceiveMessage.send(message);
			sendReceiveMessage.receive();
			sendReceiveMessage.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	/**
	 * 登陆认证
	 * @author u1
	 *
	 */
	private class MailAuthenticator extends Authenticator{

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			// TODO Auto-generated method stub
			return new PasswordAuthentication(username, passwd);
		}
		
	}
}

4.关于javamail api: 点这里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于使用JavaMail发送和读取邮件的问题,我可以给你一些简单的介绍。 首先,你需要导入JavaMail的jar包,然后创建Session对象,设置邮件服务器的配置信息和账号授权信息。例如: ```java Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.example.com"); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your_username", "your_password"); } }); ``` 然后,你可以使用Message对象来创建邮件内容,并使用Transport对象将邮件发送出去。例如: ```java Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); message.setSubject("Testing JavaMail"); message.setText("Hello World!"); Transport.send(message); ``` 如果你需要读取邮件,也可以使用JavaMail提供的API。你需要连接到邮件服务器,打开收件箱,并遍历所有邮件。例如: ```java Store store = session.getStore("pop3"); store.connect("pop3.example.com", "your_username", "your_password"); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Message[] messages = inbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message message = messages[i]; System.out.println("Subject: " + message.getSubject()); } inbox.close(false); store.close(); ``` 这只是JavaMail的简单使用方式,如果你需要更多的功能,可以参考JavaMail的官方文档或者其他相关的教程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值