作为一个屌丝程序员不得不收藏的工具类 一 邮件验证类

本文提供了一个Java程序示例,展示了如何使用JavaMail API通过SMTP发送包含文本、HTML内容、附件及内联图片的电子邮件。该示例涵盖了邮件身份验证、设置邮件属性、构建邮件正文与附件等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
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.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class SendMial2 {
	public static void main(String[] args) {
		try{
			//发件人邮箱
			String userName="xxxxxxxx@qq.com";
			//发件人密码
			String password="xxxxxxx";
			//smtp服务器地址
			String smtp_server="smtp.qq.com";
			String from_mail_address=userName;
			//收件人邮箱
			String to_mail_address="xxxxxxxx@qq.com";
			//邮件标题
			String EmailTitle="Mail Test";
			//邮件体别名
			String bodyText="验证邮件";
			//附件路径
			String attachmentPath="C:\\Users\\Administrator\\Desktop\\mail.jar";
			//文字内容
			String contentText="<a href='http://www.baidu.com'>我是链接</a>";
			//附件图片路径
			String attachmentPicPath="C:\\Users\\Administrator\\Desktop\\大法师法师法.jpg";
			
			//身份验证
			Authenticator auth=new PopupAuthenticator(userName,password);
			Properties mailProps=new Properties();
			//设置smtp服务器地址
			mailProps.put("mail.smtp.host", smtp_server);
			//使用smtp身份验证
			mailProps.put("mail.smtp.auth", "true");
			//用户名
			mailProps.put("username", userName);
			//密码
			mailProps.put("password", password);
			//登录邮箱
			Session mailSession=Session.getDefaultInstance(mailProps, auth);
			//打印日志
			//mailSession.setDebug(true);
			MimeMessage message=new MimeMessage(mailSession);
			//设置发件人邮箱
			message.setFrom(new InternetAddress(from_mail_address));
			//设置收件人邮箱  RecipientType:cc表示抄送   bcc 表示暗送
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(to_mail_address));
			//设置邮件标题
			message.setSubject(EmailTitle);
			//邮件体
			MimeMultipart multi=new MimeMultipart();
			BodyPart textBodyPart=new MimeBodyPart();
			//邮件体别名
			textBodyPart.setText(bodyText);
			//创建附件
			MimeBodyPart bodyPartAttch = createAttachMent(attachmentPath);
			//创建邮件的正文
			MimeBodyPart bodyPartContentAndPic = createContentAndPic(contentText,attachmentPicPath);//文本内容
			//添加附件
			multi.addBodyPart(bodyPartAttch);
			//添加文本内容
			multi.addBodyPart(bodyPartContentAndPic);
			//添加邮件体
			multi.addBodyPart(textBodyPart);
			//设置正文与附件之间的关系 相关的:related 混合:mixed 替代:alternative
			multi.setSubType("mixed");
			//设置邮件的邮件体
			message.setContent(multi);
			//保存修改
			message.saveChanges();
			//发送邮件
			Transport.send(message);
			System.out.println("发送成功");
		}catch(Exception ex){
			System.err.println("邮件发送失败的原因是:"+ex.getMessage());
			System.err.print("具体的错误原因:");
			ex.printStackTrace(System.err);
		}
	}
	
	//创建附件
	public static MimeBodyPart createAttachMent(String path) throws MessagingException{
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		FileDataSource dataSource = new FileDataSource( new File(path));
		mimeBodyPart.setDataHandler(new DataHandler(dataSource));
		mimeBodyPart.setFileName(dataSource.getName());
		return mimeBodyPart;
	}
	
	//创建文本和图片
	public static MimeBodyPart createContentAndPic(String content,String path) throws MessagingException{
		MimeMultipart mimeMutiPart = new MimeMultipart("related");
		//图片
		MimeBodyPart picBodyPart = new MimeBodyPart();
		FileDataSource fileDataSource = new FileDataSource( new File(path));
		picBodyPart.setDataHandler(new DataHandler(fileDataSource));
		//picBodyPart.setFileName(fileDataSource.getName());
		try {
			//解决中文乱码问题
			picBodyPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		picBodyPart.setHeader("Content-Location", path);
		mimeMutiPart.addBodyPart(picBodyPart);
		//文本
		MimeBodyPart contentBodyPart = new MimeBodyPart();
		//img的src要和setHeader中设置的值一样
		// setContent(“邮件的正文内容”,”设置邮件内容的编码方式”)
		contentBodyPart.setContent(content+"<a href='http://www.baidu.com'><img src='http://www.baidu.com/img/bdlogo.png'/></a>","text/html;charset=gbk");
		mimeMutiPart.addBodyPart(contentBodyPart);
		//图片和文本结合
		MimeBodyPart allBodyPart = new MimeBodyPart();
		allBodyPart.setContent(mimeMutiPart);
		return allBodyPart;
	}
}

class PopupAuthenticator extends Authenticator{
	private String username;
	private String password;
	
	public PopupAuthenticator(String username,String pwd){
		this.username=username;
		this.password=pwd;
	}
	
	 /**
     * 在 JavaMail 中,可以通过 extends Authenticator 抽象类,在子类中覆盖父类中的 getPasswordAuthentication() 
     * 方法,就可以实现以不同的方式来进行登录邮箱时的用户身份认证。JavaMail 中的这种设计是使用了策略模式(Strategy
     * */
	public PasswordAuthentication getPasswordAuthentication(){
		return new PasswordAuthentication(this.username,this.password);
	}
}
懒得抽方法了,有需要的同学自己抽吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值