java发送Email

使用了一个包:mail.jar


package com.delta.mes.eqm.util;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.delta.mes.eqm.Constants;

import ch.qos.logback.classic.Logger;

public class MailUtil {
	
	private Logger log;
	
	private MimeMessage mimeMsg;
	
	private Session session;
	
	private Properties props;
	
	private String username = "";
	
	private String password = "";
	
	private MimeMultipart mp;

	private boolean isCC = false;
	
	

	public MailUtil() {

	}

	public MailUtil(Logger log) {
		this.log = log;
		setSmtpHost(Constants.SMTP);
		createMimeMessage();
	}

	public void setSmtpHost(String hostName) {
		if (props == null) {
			props = System.getProperties();
		}
		props.put("mail.smtp.host", hostName);
	}

	public boolean createMimeMessage() {
		try {
			session = Session.getDefaultInstance(props, null);
		} catch (Exception e) {
			log.error("get mail session error: " + e);
			return false;
		}
		try {
			mimeMsg = new MimeMessage(session);
			mp = new MimeMultipart();
		} catch (Exception e) {
			log.error("create mail mime object error: " + e);
			return false;
		}
		return true;
	}

	public void setNeedAuth(boolean need) {
		if (props == null) {
			props = System.getProperties();
		}
		if (need) {
			props.put("mail.smtp.auth", "true");
		} else {
			props.put("mail.smtp.auth", "false");
		}
	}

	public void setNamePass(String name, String pass) {
		username = name;
		password = pass;
	}

	public boolean setSubject(String mailSubject) {
		try {
			mimeMsg.setSubject(mailSubject);
		} catch (Exception e) {
			log.error("set mail theme error: " + e);
			return false;
		}
		return true;
	}

	public boolean setBody(String mailBody) {
		try {
			BodyPart bp = new MimeBodyPart();
			bp.setText(mailBody);
			mp.addBodyPart(bp);
		} catch (Exception e) {
			log.error("set mail body error: " + e);
			return false;
		}
		return true;
	}


	public boolean addFileAffix(String filename) {
		try {
			BodyPart bp = new MimeBodyPart();
			FileDataSource fileds = new FileDataSource(filename);
			bp.setDataHandler(new DataHandler(fileds));
			bp.setFileName(fileds.getName());
			mp.addBodyPart(bp);
		} catch (Exception e) {
			log.error("add mail " + filename + " attachment error: " + e);
			return false;
		}
		return true;
	}

	public boolean setFrom(String from) {
		try {
			mimeMsg.setFrom(new InternetAddress(from));
		} catch (Exception e) {
			log.error("set mail from error: " + e);
			return false;
		}
		return true;
	}

	public boolean setTo(String to) {
		if (to == null) {
			return false;
		}
		try {
			mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
		} catch (Exception e) {
			log.error("set mail to error: " + e);
			return false;
		}
		return true;
	}

	public boolean setCopyTo(String copyto) {
		if (copyto == null) {
			return false;
		}
		try {
			mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(copyto));
		} catch (Exception e) {
			log.error("set mail copy to error: " + e);
			return false;
		}
		return true;
	}

	public boolean sendOut() {
		try {
			mimeMsg.setContent(mp);
			mimeMsg.saveChanges();
			Session mailSession = Session.getInstance(props, null);
			Transport transport = mailSession.getTransport("smtp");
			transport.connect(props.getProperty("mail.smtp.host"), username, password);
			transport.sendMessage(mimeMsg, mimeMsg.getRecipients(javax.mail.Message.RecipientType.TO));
			if (isCC) {
				transport.sendMessage(mimeMsg, mimeMsg.getRecipients(javax.mail.Message.RecipientType.CC));
			}
			transport.close();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("set mail error: " + e);
			return false;
		}
		return true;
	}

	public boolean sendMail(MailVO mailVO) {
		setSmtpHost(mailVO.getHost());
		createMimeMessage();

		if (mailVO.isAuth()) {
			this.setNeedAuth(true);
			this.setNamePass(mailVO.getUserName(), mailVO.getPassWord());
		}
		this.setSubject(mailVO.getMailTitle());
		String[] fileaffix = mailVO.getAttachment();
		if (fileaffix != null) {
			for (String file : fileaffix) {
				this.addFileAffix(file);
			}
		}
		this.setBody(mailVO.getMailContent());
		this.setFrom(mailVO.getMailFrom());
		this.setTo(mailVO.getMailTo());
		String copy = mailVO.getCopyTo();
		if (copy != null) {
			this.setCopyTo(copy);
			isCC = true;
		}
		return sendOut();
	}

	public static void main(String[] args) {
		MailVO mailVO = new MailVO();
		mailVO.setHost("xx.xx.corp");
		mailVO.setAuth(true);
		mailVO.setUserName("AA");
		mailVO.setPassWord("BB");
		mailVO.setMailTitle("title");
		mailVO.setMailTo("a@b.com,b@b.com");
		mailVO.setCopyTo("c@b.com,d@b.com");
		mailVO.setMailFrom("x@b.com");
		mailVO.setAttachment(new String[] { "e:/111.txt", "e:/222.txt" });
		mailVO.setMailContent("test");

		MailUtil themail = new MailUtil();
		boolean bol = themail.sendMail(mailVO);
		System.out.println(bol);
	}
}

package com.delta.mes.eqm.util;

import com.delta.mes.eqm.Constants;

public class MailVO {
	// mail host
	private String host = Constants.SMTP;
	// mail theme
	private String mailTitle;

	// to
	private String mailTo;

	// from
	private String mailFrom;

	// cc
	private String copyTo;

	// attachment
	private String[] attachment;

	// mail content
	private String mailContent;

	// is Auth
	private boolean isAuth = false;

	// username
	private String userName;

	// password
	private String passWord;

	public MailVO() {
	}

	public MailVO(String host, String mailTitle, String mailTo, String mailFrom, String copyTo, String[] attachment, String mailContent, boolean isAuth, String userName, String passWord) {
		super();
		this.host = host;
		this.mailTitle = mailTitle;
		this.mailTo = mailTo;
		this.mailFrom = mailFrom;
		this.copyTo = copyTo;
		this.attachment = attachment;
		this.mailContent = mailContent;
		this.isAuth = isAuth;
		this.userName = userName;
		this.passWord = passWord;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getMailTitle() {
		return mailTitle;
	}

	public void setMailTitle(String mailTitle) {
		this.mailTitle = mailTitle;
	}

	public String getMailTo() {
		return mailTo;
	}

	public void setMailTo(String mailTo) {
		this.mailTo = mailTo;
	}

	public String getMailFrom() {
		return mailFrom;
	}

	public void setMailFrom(String mailFrom) {
		this.mailFrom = mailFrom;
	}

	public String getCopyTo() {
		return copyTo;
	}

	public void setCopyTo(String copyTo) {
		this.copyTo = copyTo;
	}

	public String[] getAttachment() {
		return attachment;
	}

	public void setAttachment(String[] attachment) {
		this.attachment = attachment;
	}

	public String getMailContent() {
		return mailContent;
	}

	public void setMailContent(String mailContent) {
		this.mailContent = mailContent;
	}

	public boolean isAuth() {
		return isAuth;
	}

	public void setAuth(boolean isAuth) {
		this.isAuth = isAuth;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassWord() {
		return passWord;
	}

	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}

}


Java发送电子邮件通常需要使用JavaMail API,这是一个标准库,它提供了一组用于处理SMTP协议(简单邮件传输协议)的类。以下是一个简单的示例,展示如何使用JavaMail发送一封普通的文本邮件: ```java import javax.mail.*; import javax.mail.internet.*; public class EmailSender { public static void main(String[] args) { String from = "your-email@example.com"; String to = "recipient-email@example.com"; String password = "your-password"; // 使用应用程序密码或授权码 String host = "smtp.example.com"; // 你的SMTP服务器地址 Properties props = new Properties(); props.put("mail.smtp.auth", "true"); // 需要身份验证 props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密 props.put("mail.smtp.host", host); props.put("mail.smtp.port", "587"); // 根据你的SMTP服务器设置端口 Session session = Session.getInstance(props, new Authenticator() { // 实现Authenticator接口 protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject("测试Java邮件"); message.setText("这是一封通过Java发送的电子邮件"); Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { e.printStackTrace(); } } } ``` 在这个例子中,你需要替换`from`、`to`、`password`和`host`为你实际的邮箱信息。请注意,为了运行此代码,你需要将JavaMail API添加到你的项目中。
评论 14
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值