/**
* 获取邮箱信息
* 耿直
* qq:1293443962
*/
public class JavaMailWithAttachment {
private MimeMessage message;
private Session session;
private Transport transport;
private String mailHost = "";
private String sender_username = "";
private String sender_password = "";
private Properties properties = new Properties();
/*
* 初始化方法
*/
public JavaMailWithAttachment(boolean debug) throws GeneralSecurityException {
this.mailHost = properties.getProperty("mail.smtp.host", "smtp.qq.com");
this.sender_username = properties.getProperty("mail.sender.username", "发邮件的qq邮箱@qq.com");
this.sender_password = properties.getProperty("mail.sender.password", "到发邮件的QQ邮箱里申请");
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.socketFactory.port", "465");
session = Session.getInstance(properties);
session.setDebug(debug);// 开启后有调试信息
message = new MimeMessage(session);
}
/**
* 发送邮件
*
* @param subject 邮件主题
* @param sendHtml 邮件内容
* @param receiveUser 收件人地址
* @param attachment 附件
*/
public boolean doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
boolean flag = false;
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username);
message.setFrom(from);
// 收件人
InternetAddress to = new InternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO, to);
// 邮件主题
message.setSubject(subject);
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 添加附件的内容
if (attachment != null) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
// 将multipart对象放到message中
message.setContent(multipart);
// 保存邮件
message.saveChanges();
transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
flag = true;
System.out.println("send success!");
} catch (Exception e) {
e.printStackTrace();
flag = false;
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
return flag;
}
java发送邮件
最新推荐文章于 2025-02-08 00:00:00 发布