JavaMail 发送邮件


//邮件服务器属性
    		 Properties prop=new Properties();
    		 prop.put("mail.smtp.host", requestBody.getSmtpServer());
    		 prop.put("mail.smtp.port", requestBody.getSmtpPort());
    		 prop.put("mail.transport.protocol", "smtp");
    		 prop.put("mail.stmp.auth", "true");//验证
    		 
    		 //使用需要鉴权类
    		 Authenticator auth=new SimpleAuthenticator(requestBody.getUserName(),requestBody.getPassword());
    		 //通过邮件服务器属性来创建会话
    		 Session session=Session.getDefaultInstance(prop,auth);
    		 
    		 //创建邮件信息
    		 MimeMessage message=new MimeMessage(session);
    		 
    		 //创建发送人
    		 message.setFrom(new InternetAddress(request.getRequestBody().getMessage().getFrom()));
    		 
    		 //收件人
    		 int receiverLength=request.getRequestBody().getMessage().getTo().length;
    		 InternetAddress[] send=new InternetAddress[receiverLength];
    		 for(int i=0;i<receiverLength;i++){
    			 send[i]=new InternetAddress(request.getRequestBody().getMessage().getTo()[i]);
    		 }
    		 message.setRecipients(Message.RecipientType.TO, send);
    		 
    		 //添加抄送
    		 int cclength=requestBody.getMessage().getCc().length;
    		 InternetAddress[] sendcc=new InternetAddress[cclength];
    		 for(int i=0;i<cclength;i++){
    			 sendcc[i]=new InternetAddress(requestBody.getMessage().getCc()[i]);
    		 }
    		 message.setRecipients(Message.RecipientType.CC, sendcc);
    		 //添加邮件主题
    		 message.setSubject(request.getRequestBody().getMessage().getSubject());
    		 //添加发送日期
    		 message.setSentDate(new java.util.Date());
    		 // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
 			Multipart multipart=new MimeMultipart();
 			BodyPart contentPart=new MimeBodyPart();
 			contentPart.setText("");
 			multipart.addBodyPart(contentPart);

你可能感兴趣的:(java,smtp)