使用JavaMail发邮件

public class EmailUtil {
	public static void sendEmail(String smtpHost, String senderAddress, String senderName,
					String receiverAddress, String sub, String content) throws Exception {
		List<String> recipients = new ArrayList<String>();
		recipients.add(receiverAddress);

		sendEmail(smtpHost, senderAddress, senderName, recipients, sub, content);
	}

	public static void sendEmail(String smtpHost, String senderAddress, String senderName,
					List<String> recipients, String sub, String content) throws Exception {
		if (smtpHost == null) {
			String errMsg = "Could not send email: smtp host address is null";
			
			throw new Exception(errMsg);
		}

		try {
			Properties props = System.getProperties();
			props.put("mail.smtp.host", smtpHost);
			props.put("mail.smtp.port", "25");
		    props.put("mail.smtp.auth", "true");

			Session session = Session.getDefaultInstance(props,null );
			MimeMessage message = new MimeMessage( session );
			message.setSubject(sub,"UTF-8");			
			message.setFrom(new InternetAddress(senderAddress, senderName));
			for (String recipient : recipients) {
				message.addRecipients(Message.RecipientType.TO, recipient);
			}		
			
			Multipart mp = new MimeMultipart("related");    
	        MimeBodyPart mbp = new MimeBodyPart();    
	   
	        // 设定邮件内容的类型为 text/html    
	        mbp.setContent(content, "text/html;charset=UTF-8");    
	        mp.addBodyPart(mbp);    
	        
	     // 新建一个存放附件的BodyPart
	        mbp = new MimeBodyPart(); 
	        byte[]  bytes=new byte[]{};
	        FileInputStream  fis=new FileInputStream("F:/shu.jpg");
	        DataHandler dh = new DataHandler(new ByteArrayDataSource(fis,"application/octet-stream"));
	        mbp.setDataHandler(dh); 
	        // 加上这句将作为附件发送,否则将作为信件的文本内容
	        mbp.setFileName("1.jpg"); 
	        mbp.setHeader("Content-ID", "IMG1" );
	        // 将含有附件的BodyPart加入到MimeMultipart对象中
	        mp.addBodyPart(mbp); 
	        message.setContent(mp);  
			message.setSentDate( new Date() );		
			message.saveChanges();
			 Transport   transport=session.getTransport("smtp");   
			  transport.connect(smtpHost,"hu_wei118","password");   
			  transport.sendMessage(message,message.getAllRecipients());
			  transport.close();
		 } catch (Exception e) {
				throw new Exception("errorMsg", e);
		 }
	}
}

 

 

 

所需包:activation.jar      mail.jar

给一个人发邮件

 

web应用中调用EmailUtil.sendEmail("smtp.163.com", "[email protected]", "XX",
      "[email protected]", "Test", "你好!");

给N个人发邮件

web应用中调用

List<String>    list=new ArrayList<String>();

list.add([email protected]);

list.add([email protected]);

list.add([email protected]);

EmailUtil.sendEmail("smtp.163.com", "[email protected]", "XX", list,
          "Test", "你好!");

你可能感兴趣的:(html,Web,F#)