JODD mail 发送带附件的邮件

 最近编写了邮件功能的代码, 在附件位置可以将附件位置传入,但是为了防止位置找不到,这里我用传入了流,但是这样有弊端,多附件的时候不容易拓展。。。。

import cn.cmschina.article.dto.EmailInfo;
import jodd.mail.Email;
import jodd.mail.EmailAttachment;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpServer;
import jodd.mail.att.FileAttachment;
import jodd.petite.meta.PetiteBean;

/**
 * 带附件邮件发送
 * @author lzw
 * @Date 2019年2月20日
 */
@PetiteBean("emailSendUtil")
public class EmailSendUtil {

	private String smtpHost = null;
	
	public String sendEmailTo(EmailInfo info) throws Exception{
		String log = "";
		try {
			String user = info.getFrom().split("@")[0];
			@SuppressWarnings("rawtypes")
			SmtpServer smtpServer = SmtpServer.create(smtpHost,25)
		                .authenticateWith(user, info.getPassword());

		    Email email = Email.create()
		                .from(info.getFrom())
		                .subject(info.getSubject());
		   log +="服务器地址:"+ smtpHost;
	        if (null != info.getText()) {
	        	//正文
	        	 email.addText(info.getText());
			}
	        
	        //收件人
	        email.to(info.getTo());
	        if (null != info.getFile() && null != info.getFilename()) {
	        	String filename = info.getFilename();
		        //截取文件名
		        //String filename = filepath.substring(filepath.lastIndexOf("/")+1);
		        //截取文件类型
		        String pdf = filename.substring(filename.indexOf(".")+1);
		        EmailAttachment attachment = new FileAttachment(
		                info.getFile(),filename,pdf);
		        //设置附件
		        email.attach(attachment);
			}
	        
	        log += "Eamil对象:"+email.toString();
	        SendMailSession session = smtpServer.createSession();
	        
	        session.open();
	        session.sendMail(email);
	        session.close();
	        return log;
		} catch (Exception e) {
			e.printStackTrace();
			log+="异常信息:"+e;
			throw new Exception(log);
		}
	}
}
/**
 * @author lzw
 * @Date 2019年2月22日
 */
@PetiteBean("email")
public class EmailApi extends BaseApi implements AuthNone {


	@Setter
	@PetiteInject
	private EmailSendUtil emailUtil;
	
	@AuthExclude(internetForbidden = false)
	public String Email(Message msg) throws Exception{
		EmailInfo paramBean = getParamBean(msg, EmailInfo.class);
		String path = System.getProperty("user.dir");
		paramBean.setFile(new File("C:/Users/HP/Desktop/aaa.pdf"));
		paramBean.setFilename("aaa.pdf");
		paramBean.setFrom("[email protected]");
		paramBean.setPassword("123456Qw");
		paramBean.setSubject("主题");
		paramBean.setText("正文");
		paramBean.setTo("[email protected]");
		String string = emailUtil.sendEmailTo(paramBean);
		return CommonUtil.success(string);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42228950/article/details/87910960