Java实现发送邮件

首先我们在官网下载jar包http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-eeplat-419426.html#javamail-1.4.5-oth-JPR

Java实现发送邮件_第1张图片
我们只需要这个mail.jar

新建一个项目导入次jar包

Java实现发送邮件_第2张图片


写测试方法

public static void SendEmail(){
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");//使用的协议
		props.setProperty("mail.smtp.host", "smtp.163.com");
		props.setProperty("mail.smtp.port", "465");//端口
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.smtp.ssl.enable", "true");
		Session session = Session.getDefaultInstance(props);
		//创建邮件
		MimeMessage message = createEmail(session);
		Transport transport;
		try {
			transport = session.getTransport();
			try {
				transport.connect("smtp.163.com","你的邮箱地址","你的邮箱密码");
				//发送邮件
				transport.sendMessage(message, message.getAllRecipients());
				transport.close();
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (NoSuchProviderException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}

createEmail方法如下

public static MimeMessage createEmail(Session session){
		MimeMessage msg = new MimeMessage(session);
		try {
			InternetAddress fromAddress = new InternetAddress("你的邮箱地址","昵称","utf-8");
			try {
				msg.setFrom(fromAddress);
				InternetAddress receiveAddress = new InternetAddress("接收方邮箱","接收方姓名","utf-8");
				msg.setRecipient(RecipientType.TO, receiveAddress);
				//设置标题
				msg.setSubject("标题","utf-8");
				//设置正文
				msg.setText("正文");
				msg.setSentDate(new Date());//设置发送时间
				msg.saveChanges();
				
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return msg;
		
	}

运行结果:

Java实现发送邮件_第3张图片


本方法参考自:https://blog.csdn.net/qq_28268507/article/details/74316065

侵删


你可能感兴趣的:(Java)