如何用JavaMail完成各类邮件的发送

Email就是电子邮件,电子邮件的收发在我们日常生活中也比较常用,我们常用的邮件软件有:网易邮箱、QQ邮箱、Foxmail等都可以用来收发邮件,当然了java程序也可以收发邮件,接下来就让我们来看一看如何用JavaMail完成各类邮件的发送。

 那么我们先来看一下电子邮件的发送过程:电子邮件由用户电脑的电子邮箱发送至邮件服务器上,经过若干邮件服务器的中转,最终到达对方邮件服务器上,收件方就可以用软件接收邮件了。如图所示:

 我们要用Java程序来发送邮件就是要编写邮件发送方的邮箱,并将邮件发送到邮件服务器上。邮箱到邮件服务器发送邮件的协议就是SMTP协议,使用标准端口号25.

任何程序发送邮件都必须遵守SMTP协议,在这里我们不需要了解SMTP协议的底层原理,只需要使用JavaMail这个标准API就可以直接发送邮件。

1.先创建工具类(用以创建Session会话)

在这里我们创建一个无法实例化的工具类IS_SMTP,它的作用仅是通过调用它里面的静态方法createSession()来创建Session会话

package com.aPesource.day2;


import javax.mail.PasswordAuthentication;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Session;

public class IS_SMTP {
	private IS_SMTP() {
		
	}
	public static Session createSession(){
//		邮箱账号信息
		String userName="13992631384@163.com";//发送方邮箱账号
		String password="FCPQKFHFDHJFTSXA";//账号授权密码
		
//		SMTP服务器连接信息
		Properties props=new Properties();
		props.put("mail.smtp.host", "smtp.163.com");//SMTP主机名
		props.put("mail.smtp.prot", "25");//主机端口号
		props.put("mail.smtp.auth", "true");//是否需要用户认证
		props.put("mail.smtp.starttls.enable","true");//启用TLS加密
		
		
//		创建Session会话
//		参数1:smtp服务器连接参数
//		参数2:账号和密码的授权认证对象
		Session session=Session.getInstance(props,new Authenticator() {
			protected PasswordAuthentication  getPasswordAuthentication() {
				return new PasswordAuthentication(userName, password);
			}
		});
		return session;
	}
}

在这里我以163邮箱来作为发送邮箱,进入163邮箱后点击设置,点击POP3/SMTP/IMAP,如图所示,点击标红区

 之后会出现一个二维码,扫描二维码发送信息即可获取账号授权密码。

我们要先把JavaMail相关的依赖jar包加入至当前项目;

在SMTP服务器连接信息中smtp主机名中:163邮箱是:smtp.163.com

QQ邮箱:smtp.qq.com

Gmail邮箱:smtp.gmail.com

2.发送文件

(1).发送普通文本内容的文件

发送邮件时,我们需要创建一个MimeMessage对象,再设置邮件的内容,加上发件人与收件人,最后调用Transport.send()即可完成发送。

package com.aPesource.day2;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class IS_exmail2 {
	public static void main(String[] args) {
		
		try {
//			1.创建Session会话
			Session session=IS_SMTP.createSession();
			
//			2.创建邮件对象
			MimeMessage message=new MimeMessage(session);
			message.setSubject("发送一份邮件的标题");//设置邮件标题
			message.setText("啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦","utf-8");//设置邮件正文
			message.setFrom(new InternetAddress("13992632384@163.com"));
			message.setRecipient(RecipientType.TO, new InternetAddress("2893797168@qq.com"));
			
//			3.发送
			Transport.send(message);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

(2)发送HTML文件

只需要将setText中加上"html",例如:

message.setText("<b>啦啦啦啦</b>啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦","utf-8","html");

这样就可以识别文本中的HTML标签了

(3)发送带附件的邮件

只需要在构造一个Multipart对象即可

package com.aPesource.day2;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

public class IS_exmail {
	public static void main(String[] args) {
		
		try {
			Session session=IS_SMTP.createSession();
			MimeMessage message=new MimeMessage(session);
			
			message.setSubject("我们的故事开启");
//			message.setText("对面的妹妹理我一下嘛","utf-8","html");
			message.setFrom(new InternetAddress("13995734354@163.com"));//发件人
			message.setRecipient(RecipientType.TO, new InternetAddress("2673455196@qq.com"));//收件人
			message.setRecipients(RecipientType.CC,new InternetAddress[] {new InternetAddress("1161563710@qq.com"),new InternetAddress("1941665540@qq.com"),new InternetAddress("1329337516@qq.com"),new InternetAddress("3197898106@qq.com")});//群发(抄送多人)
            BodyPart textPart=new MimeBodyPart();
            textPart.setContent("<b>慕名而来,认识一下</b>","text/html;charset=utf-8");
            BodyPart filePart=new MimeBodyPart();
			filePart.setFileName("爱你");
			try {
				filePart.setDataHandler(
						new DataHandler(
								new ByteArrayDataSource(
										Files.readAllBytes(Paths.get("C:\\Users\\Lenovo\\Desktop\\微信图片_20230708095429.jpg")),"application/octet-stream"
										)));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			filePart.setHeader("Content-ID", "cbkj");
					
			Multipart multipart=new MimeMultipart();
			multipart.addBodyPart(textPart);
			multipart.addBodyPart(filePart);
            message.setContent(multipart);
			Transport.send(message);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

(4)邮件正文嵌套图片

package com.aPesource.day2;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

public class IS_exmail {
	public static void main(String[] args) {
		
		try {
			Session session=IS_SMTP.createSession();
			MimeMessage message=new MimeMessage(session);
			
			message.setSubject("我们的故事开启");
//			message.setText("对面的妹妹理我一下嘛","utf-8","html");
			message.setFrom(new InternetAddress("13992731394@163.com"));//发件人
			message.setRecipient(RecipientType.TO, new InternetAddress("2693465176@qq.com"));//收件人
			message.setRecipients(RecipientType.CC,new InternetAddress[] {new InternetAddress("1161543710@qq.com"),new InternetAddress("1941765040@qq.com"),new InternetAddress("1319336516@qq.com"),new InternetAddress("3197898005@qq.com")});//群发(抄送多人)
			
			BodyPart textPart=new MimeBodyPart();
			StringBuilder contentText=new StringBuilder();
			contentText.append("<h3>缘分</h3>");
//			textPart.setContent("<b>慕名而来,认识一下</b>","text/html;charset=utf-8");
			contentText.append("<p>慕名而来,认识一下</p>");
			contentText.append("<img src=\"cid:cbkj\"/>");
			textPart.setContent(contentText.toString(),"text/html;charset=utf-8");
			
			
			
			BodyPart filePart=new MimeBodyPart();
//			filePart.setFileName("爱你");
			try {
				filePart.setDataHandler(
						new DataHandler(
								new ByteArrayDataSource(
										Files.readAllBytes(Paths.get("C:\\Users\\Lenovo\\Desktop\\微信图片_20230708095429.jpg")),"application/octet-stream"
										)));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			filePart.setHeader("Content-ID", "cbkj");
					
			Multipart multipart=new MimeMultipart();
			multipart.addBodyPart(textPart);
			multipart.addBodyPart(filePart);
			
			message.setContent(multipart);
			Transport.send(message);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值