Java Email邮件的发送

一、导入两个jar包

用于发送邮件的两个jar包

 二、创建邮箱工具类JavaMailUtils

public final class JavaMailUtils {
	private JavaMailUtils() {
		
	}
	public static Session createSession() {
		String username="*************@163.com";//登录用户名
		String password="*************";//登录口令
        // 连接到SMTP服务器:
		Properties props=new Properties();
		props.put("mail.smtp.host", "smtp.163.com");//主机名
		props.put("mail.smtp.port", "25");//端口号
		props.put("mail.smtp.auth", "true");//是否需要用户验证
		props.put("mail.smtp.starttls.enable", "true");//启用TLS加密
        //获取Session实例:
		Session session=Session.getInstance(props,new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username,password);
			}
		});
		session.setDebug(true);
		return session;//设置debug模式便于调试:
	}
}

三、发送邮件

public class Email {
    public static void main(String[] args) {
            try {
                //创建session对象
                Session session = JavaMailUtils.createSession();
                //创建邮件对象
                MimeMessage message = new MimeMessage(session);
                // 设置邮件主题:
                message.setSubject("Hello", "UTF-8");
                // 设置邮件正文:
                message.setText("Hi Xiaoming...", "UTF-8");
                message.setFrom(new InternetAddress("18220748226@163.com"));//发件人地址

                message.setRecipient(RecipientType.TO, new InternetAddress("3110202314@qq.com"));//设置接收方地址
                Transport.send(message);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

发送HTML邮件

 发送HTML邮件和文本邮件是类似的,只需要把:

message.setText(body, "UTF-8");改为message.setText(body, "UTF-8", "html");

传入的body是类似<h1>Hello</h1><p>Hi, xxx</p>这样的HTML字符串即可。

public class email2 {
	public static void main(String[] args) {
		try {
			Session session = JavaMailUtils.createSession();
			MimeMessage message = new MimeMessage(session);
			message.setSubject("这是<h1>一封</h1>测试邮件","utf-8");
			message.setText("你好,我是<b>李逵</b>","utf-8","html");
			message.setFrom(new InternetAddress("***********@163.com"));//发件人
			message.setRecipient(RecipientType.TO, new InternetAddress("3110202314@qq.com"));
			Transport.send(message);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
}

发送带有附件的邮件 

public class Email3 {
	public static void main(String[] args) {
		try {
			Session session = JavaMailUtils.createSession();
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress("**********@163.com"));//发件人
			message.setRecipient(RecipientType.TO, new InternetAddress("*********@qq.com"));//主收件人
			message.setRecipients(RecipientType.CC, new InternetAddress[] { new InternetAddress("*********@qq.com"),new InternetAddress("************@qq.com") });//抄送人
			message.setSubject("鸡汤邮件");			
			BodyPart textPart=new MimeBodyPart();
			textPart.setContent("用<b>脑子</b>干事算是工作。","text/html;charset=utf-8");
			BodyPart filePart=new MimeBodyPart();
			filePart.setFileName("图片");
			filePart.setDataHandler(new DataHandler(new ByteArrayDataSource(Files.readAllBytes(Paths.get("C:\\Users\\Pictures\\Frostpunk\\1.png")),"application/octet-stream")));
			Multipart multipart=new MimeMultipart();
			multipart.addBodyPart(textPart);
			multipart.addBodyPart(filePart);
			message.setContent(multipart);
			Transport.send(message);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

发送内嵌图片的HTML邮件
如果需要在HTML邮件中内嵌图片,可以选择在邮件中加入<img src="http://example.com/test.jpg">,这样的外部图片链接通常会被邮件客户端过滤,并提示用户显示图片并不安全。只有内嵌的图片才能正常在邮件中显示。所以,这种方式并不推荐。
推荐将内嵌图片作为一个附件嵌入邮件,即邮件本身也是Multipart,但需要做一点额外的处理: 

Multipart multipart = new MimeMultipart();
					
// 添加text:
BodyPart textpart = new MimeBodyPart();
textpart.setContent("<h1>Hello</h1><p><img src=\"cid:img01\"></p>", "text/html;charset=utf-8");
multipart.addBodyPart(textpart);

// 添加image:
BodyPart imagepart = new MimeBodyPart();
imagepart.setFileName("lvjuren.jpg");
imagepart.setDataHandler(new DataHandler(new ByteArrayDataSource(new FileInputStream("c:\\test\\lvjuren.jpg"), "application/octet-stream")));
multipart.addBodyPart(imagepart);

// 设置当前image为内嵌图片
// 这个ID和HTML中引用的ID对应起来,邮件客户端就可以正常显示内嵌图片
imagepart.setHeader("Content-ID", "<img01>");

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猿究◎小飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值