struts2+javamail实现邮件发送


要实现邮件发送需要用到mail.jar这个jar包,大家可以去官网下载一个。


package com.jxust.util;

import java.io.File;
import java.io.IOException;   
import java.util.Date;   
import java.util.Properties;   
    
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;   
import javax.mail.Message;   
import javax.mail.MessagingException;   
import javax.mail.Multipart;   
import javax.mail.PasswordAuthentication;   
import javax.mail.Session;   
import javax.mail.Transport;   
import javax.mail.internet.AddressException;   
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;

import org.apache.struts2.ServletActionContext;

public class MailSenderUtil {
	
	public  void sendEmailWithAttachments(String host, String port,  
	            final String userName, final String password, String toAddress,  
	            String subject, String message, String[] attachFiles)  
	            throws AddressException, MessagingException {  
	        // sets SMTP server properties  
	        Properties properties = new Properties();  
	        properties.put("mail.smtp.host", host);  //设置邮箱服务器属性
	        properties.put("mail.smtp.port", port);  //定义邮箱接口属性
	        properties.put("mail.smtp.auth", "true");  //是否需要邮箱验证
	        properties.put("mail.smtp.starttls.enable", "true");  
	        properties.put("mail.user", userName);  //邮箱用户
	        properties.put("mail.password", password);  //用户密码
	  
	        // creates a new session with an authenticator  
	        Authenticator auth = new Authenticator() {  
	            public PasswordAuthentication getPasswordAuthentication() {  
	                return new PasswordAuthentication(userName, password);  
	            }  
	        };  
	        Session session = Session.getInstance(properties, auth);  
	  
	        // creates a new e-mail message  
	        Message msg = new MimeMessage(session);  
	  
	        msg.setFrom(new InternetAddress(userName));  
	        InternetAddress[] toAddresses = { new InternetAddress(toAddress) };  
	        msg.setRecipients(Message.RecipientType.TO, toAddresses);  
	        msg.setSubject(subject);  
	        msg.setSentDate(new Date());  
	  
	        // creates message part  
	        MimeBodyPart messageBodyPart = new MimeBodyPart();  
	        messageBodyPart.setContent(message, "text/html");  
	  
	        // creates multi-part  
	        Multipart multipart = new MimeMultipart();  
	        multipart.addBodyPart(messageBodyPart);  
	  
	        // adds attachments  
	        if (attachFiles != null && attachFiles.length > 0) {  
	            for (String filePath : attachFiles) {  
	                MimeBodyPart attachPart = new MimeBodyPart();  
	            	
	                      
	                try {  
	                	 File file=new File(filePath);
	                       FileDataSource dataSource = new FileDataSource(file);
	                       attachPart.setDataHandler(new DataHandler(dataSource));
	                       //MimeUtility.encodeText(dataSource.getName())解决中文乱码问题;
	                       attachPart.setFileName(MimeUtility.encodeText(dataSource.getName()));                   
	                } catch (Exception ex) {  
	                    ex.printStackTrace();  
	                }  
	  
	                multipart.addBodyPart(attachPart);  
	            }  
	        }  
	  
	        // sets the multi-part as e-mail's content  
	        msg.setContent(multipart);  
	  
	        // sends the e-mail  
	        Transport.send(msg);  
	  
	    }  
}

下面是一个简单的使用的例子:

package com.jxust.action;

import org.apache.struts2.ServletActionContext;

import com.jxust.util.MailSenderUtil;
import com.opensymphony.xwork2.ActionSupport;

public class MailSenderAction extends ActionSupport{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private MailSenderUtil mailSenderUtil;
	public MailSenderUtil getMailSenderUtil() {
		return mailSenderUtil;
	}
	public void setMailSenderUtil(MailSenderUtil mailSenderUtil) {
		this.mailSenderUtil = mailSenderUtil;
	}
	public String sendMail()throws Exception{
		  // 发件人信息  
        String host = "smtp.qq.com";  //调用的smtp服务器
        String port = "25";  //smtp协议端口号
        String mailFrom = "xxxxx@qq.com";//发件人  
        String password = "xxxxxxxx";  //邮箱密码
  
        // 收件人信息  
        String mailTo = "xxxxx@qq.com";  //收件人
        String subject = "javaMail";//邮件标题
        String oldStr="这是一封由javaMail自动发出的测试邮件,请勿回复。";//正文
        String message =  new String(oldStr.getBytes(), "ISO8859-1");  //解决中文乱码  
  
        // 附件  
        String[] attachFiles = new String[1];  
        String FilePath=ServletActionContext.getServletContext().getRealPath("/images/测试.txt");
        attachFiles[0] =FilePath;  
        try {  
        	if(mailSenderUtil==null){
        		mailSenderUtil=new MailSenderUtil();
        	}
        	mailSenderUtil.sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
        			subject, message, attachFiles);
        	 
            System.out.println("邮件发送成功.");  
        } catch (Exception ex) {  
            System.out.println("发送失败");  
            ex.printStackTrace();  
        }  
		return"toSend";
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值