Java 发送邮件

本篇文章介绍了一个完整的Java发送邮件Web程序,首先在IDE中新建Java Web项目,导入mail.jar与topbpm-console-service.jar。

WebContent下新建HTML文件,代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML</title>
<script type="text/javascript">
    function seedEmail(){
    	var email = document.getElementById("getEmail").value;
		window.location.href='http://localhost:8080/SeedMailTest/email?email=' + email;
	}
</script>
</head>
<body>
<div align="center" style="margin:300px auto">
		邮箱:<input id="getEmail" type="text"><br>
		<button οnclick="seedEmail()">发送</button>
	</div>
</body>
</html>

发送邮件逻辑,Controller层代码如下:

@WebServlet("/email")
public class Client extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email").toString();
		String emailSuffix = ""; //163.com
		String addresser = "";//发件人163邮箱
		String password = "";//发件人邮箱密码
		try {
			//To 审批人 Content
			StringBuffer emailMsg = new StringBuffer();
			emailMsg.append("<h3>审批通知:</h3>");
			emailMsg.append("<p>借款人:" + "模拟信息" + "</p>");
			emailMsg.append("<p>借款人证件号:" + "模拟信息" + "</p>");
			emailMsg.append("<p>所属公司:" + "模拟信息"+ "</p>");
			emailMsg.append("<p>借款金额:" + "模拟信息" + "</p>");
			emailMsg.append("<p>借款期数:" + "模拟信息" + "</p>");
			emailMsg.append("<p>借款人开户行:" + "模拟信息" +"</p>");
			emailMsg.append("<p>工资卡号:" + "模拟信息" + "</p>");
			emailMsg.append("<p>请尽快审批,谢谢。</p>");
			emailMsg.append("<strong>"+ "模拟信息" + "</strong><br>");
			String[] copyPerson = null;
			//发邮件给审批人
			SendEmail.sendEmail(addresser,
					email,password,emailSuffix,copyPerson,emailMsg.toString(),"","");
			 PrintWriter out = response.getWriter();
			 out.println(
			            "<html>\n" +
			            "<head><title>" + "</title></head>\n" +
			            "<body bgcolor=\"#f0f0f0\">\n" +
			            "<h1 align=\"center\">" + "Success" + "</h1>\n" +
			            "</body></html>");
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			PrintWriter out = response.getWriter();
			out.println(
		            "<html>\n" +
		            "<head><title>" + "</title></head>\n" +
		            "<body bgcolor=\"#f0f0f0\">\n" +
		            "<h1 align=\"center\">" + "Abnormal email" + "</h1>\n" +
		            "</body></html>");
			e.printStackTrace();
		}
	}
}

SeedEmail工具类代码:

public class SendEmail {
	private static String ALIDM_SMTP_HOST = "smtp.";
    private static final int ALIDM_SMTP_PORT = 25;

	/**
	 * To 审批人
	 * @param addresser
	 * @param recipient
	 * @param password
	 * @param emailSuffix
	 * @param copyPerson
	 * @param emailContent
	 * @param filePath
	 * @param fileName
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public static void sendEmail(String addresser ,String recipient,
    		String password,String emailSuffix, String[] copyPerson ,String emailContent,String filePath,String fileName) throws MessagingException, UnsupportedEncodingException{
    	 // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示SMTP发送邮件,需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", ALIDM_SMTP_HOST + emailSuffix);
        props.put("mail.smtp.port", ALIDM_SMTP_PORT);   
        // 发件人的账号
        props.put("mail.user", addresser);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", password);

        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form = new InternetAddress(
                props.getProperty("mail.user"));
        message.setFrom(form);
        // 设置收件人
        InternetAddress to = new InternetAddress(recipient);
        message.setRecipient(MimeMessage.RecipientType.TO, to);

        // 抄送人信息   注:此处可写成循环形式
        if(copyPerson != null){
        	StringBuilder sendPerson = new StringBuilder(); 
        	for(String address : copyPerson){
        		sendPerson.append(address).append(",");
        	}
        	message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(sendPerson.substring(0,sendPerson.lastIndexOf(",")).toString()));
        	
        }
        // 设置邮件标题
        message.setSubject(MimeUtility.encodeText("放款通知", "GBK", "B"));
        //message.setSubject("=?UTF-8?B?" + Base64.encode("放款通知".getBytes("UTF-8")) + "?=");//如乱码使用
        // 设置邮件的内容体
        StringBuffer emailMsg = new StringBuffer();
        emailMsg.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">")
        .append("<html>")  
        .append("<head>")  
        .append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">")  
        .append("<title>放款通知</title>")
        .append("<style type=\"text/css\">")
        .append("p{ text-indent:4em;}")
        .append("</style>")
        .append("</head>")  
        .append("<body>")
        .append(emailContent)
        .append("</body>")  
        .append("</html>");

        // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
        Multipart multipart = new MimeMultipart();         
        //   设置邮件的文本内容
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(emailMsg.toString(), "text/html;charset=UTF-8");
        multipart.addBodyPart(contentPart);
        //添加附件
        if(StringUtil.isNotBlank(filePath) && StringUtil.isNotBlank(fileName)){
        	message.setSubject("放款通知");
	        BodyPart messageBodyPart= new MimeBodyPart();
	        
	        File sendFile = new File(filePath);
	        if(!sendFile.exists()){
	        	sendFile.mkdirs();
	        }
	        DataSource source = new FileDataSource(new File(filePath + "/"+ fileName));
	        //添加附件的内容
	        messageBodyPart.setDataHandler(new DataHandler(source));
	        //添加附件的标题
	        //这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
	        sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
	        try {
	        	fileName = MimeUtility.encodeText(fileName);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
	        fileName = fileName.replaceAll("\r", "").replaceAll("\n", "");
	        messageBodyPart.setFileName(fileName);
	        multipart.addBodyPart(messageBodyPart);
        } else {
        	 message.setSubject("审批通知");
        }
        //将multipart对象放到message中
        message.setContent(multipart);
        // 发送邮件
        Transport.send(message);
    }
}

GitHub源码地址:https://github.com/Sheamusren/SeedMail

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值