发邮件


package com.renesola.email.util;

import java.util.Date;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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 com.renesola.email.obj.AccountAuthenticator;
import com.renesola.email.obj.MailSenderInfo;
import com.renesola.framework.util.StringUtil;
import com.renesola.web.dao.WebFinalSQL;
import com.renesola.web.obj.WebFinalObj;

public class EmailUtil {

private static EmailUtil instance = new EmailUtil();

public static EmailUtil getInstance() {
return instance;
}

protected EmailUtil() {

}

public MailSenderInfo getMailSenderInfo(String name){
MailSenderInfo obj=new MailSenderInfo();
if(!StringUtil.isEmpty(name)){
WebFinalObj finalObj = WebFinalSQL.getInstance().doRead(name);
if(finalObj != null){
String txt = finalObj.getRemark();
String[] str = StringUtil.splits(txt, "\n", "", true, true);
String[] strNew = new String[str.length];
for(int i=0;i<str.length;i++){
strNew[i] = str[i].substring(str[i].lastIndexOf("=") + 1);
}
obj.setMailServerHost(strNew[0]);
obj.setMailServerPort(strNew[1]);
obj.setFromAddress(strNew[2]);
obj.setUsername(strNew[3]);
obj.setPassword(strNew[4]);
obj.setEncoding(strNew[5]);
obj.setValidate(change(strNew[6]));
}
}
return obj;
}

private boolean change(String str){
if("true".equals(str)){
return true;
}else{
return false;
}
}

public InternetAddress[] getAddress(String[] addresses) throws AddressException {
InternetAddress[] objs = null;
if (addresses != null && addresses.length > 0) {
objs = new InternetAddress[addresses.length];
for (int i = 0; i < addresses.length; i++) {
objs[i] = new InternetAddress(addresses[i]);
}
}
return objs;
}

public boolean doSend(MailSenderInfo info) {
// 判断是否需要身份认证
AccountAuthenticator authenticator = null;
// 如果需要身份认证,则创建一个密码验证器
if (info.isValidate()) {
authenticator = new AccountAuthenticator(info.getUsername(), info.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(info.getProperties(), authenticator);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(info.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address[] to = getAddress(info.getToAddress());
// Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage.setRecipients(Message.RecipientType.TO, to);
// 设置邮件消息的主题
mailMessage.setSubject(info.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(info.getContent(), "text/html; charset=" + info.getEncoding());
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
// 发送邮件
Transport.send(mailMessage);
//StringUtil.printObj(info);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}

public static void main(String[] args) {
MailSenderInfo info = new MailSenderInfo();
info.setMailServerHost("mail.renesola.com");
info.setMailServerPort("25");
info.setUsername("newsletter");
info.setPassword("A1s2d3f4");
info.setFromAddress("newsletter@renesola.com");
info.setToAddress("2210071634@qq.com");
info.setSubject("test");
info.setContent("<html><div id='mailContentContainer' style='font-size: 14px; padding: 0px; height: auto; margin-right: 170px;'>Dear Sir/Miss:<br><br>  Thank you for registering Renesola, You only need to click on the following link to activate your account, you will be able to enjoy Renesola services.<br><br>  <a target='_blank' href='http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/theme/shop/_activationEmail.html?userid=&email=' style=' color: #2a586f; text-decoration:underline!important;'>http://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/theme/shop/_activationEmail.html?userid=&email=</a><br><br>  (If you can not click on the URL link address, copy it and paste it into your browser's address input box, and then press Enter.)<br><br><br>With best regards,<br>Renesola.com</div><html>");
EmailUtil.getInstance().doSend(info);
}

public boolean sendUserRegister(String userid, String email){
MailSenderInfo info = getMailSenderInfo("email.server");
info.setToAddress(email);
String content=WebFinalSQL.getInstance().doRead("email.user.register").getRemark();
content=StringUtil.replace(content, "{userid}", userid);
content=StringUtil.replace(content, "{email}", email);
info.setSubject(WebFinalSQL.getInstance().doRead("email.user.register").getType());
info.setContent(content);
return doSend(info);
}

public boolean sendUserReplacePassword(String username,String password){
MailSenderInfo info = getMailSenderInfo("email.server");
info.setToAddress(username);
String content=WebFinalSQL.getInstance().doRead("email.user.forgetpassword").getRemark();
content=StringUtil.replace(content, "{username}", username);
content=StringUtil.replace(content, "{password}", password);
info.setSubject(WebFinalSQL.getInstance().doRead("email.user.forgetpassword").getType());
info.setContent(content);
return doSend(info);
}

}




import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class AccountAuthenticator extends Authenticator{

protected String username=null;
protected String password=null;

public AccountAuthenticator(){
}
public AccountAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}

}



package com.renesola.email.obj;

import java.util.Properties;

public class MailSenderInfo {

protected String mailServerHost;

protected String mailServerPort;

protected String fromAddress;

protected String username;

protected String password;

protected String[] toAddress;

protected String[] ccAddress;

protected String[] bccAddress;

protected String subject;

protected String content;

protected String encoding;

protected String[] attachments;

protected boolean validate;

protected Properties properties = null;

public MailSenderInfo() {
encoding = "utf-8";
}

public MailSenderInfo(String mailServerHost, String mailServerPort, String username, String password, String fromAddress, String toAddress, String subject, String content) {
encoding = "utf-8";
this.mailServerHost = mailServerHost;
this.mailServerPort = mailServerPort;
this.username = username;
this.password = password;
this.fromAddress = fromAddress;
this.toAddress = new String[] { toAddress };
this.subject = subject;
this.content = content;
}

public Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.put("mail.smtp.host", this.mailServerHost);
properties.put("mail.smtp.port", this.mailServerPort);
properties.put("mail.smtp.auth", validate ? "true" : "false");
}
return properties;
}

public String getMailServerHost() {
return mailServerHost;
}

public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}

public String getMailServerPort() {
return mailServerPort;
}

public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}

public String getFromAddress() {
return fromAddress;
}

public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}

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;
}

public String[] getToAddress() {
return toAddress;
}

public void setToAddress(String[] toAddress) {
this.toAddress = toAddress;
}

public void setToAddress(String toAddress) {
this.toAddress = new String[] { toAddress };
}

public String[] getCcAddress() {
return ccAddress;
}

public void setCcAddress(String[] ccAddress) {
this.ccAddress = ccAddress;
}

public String[] getBccAddress() {
return bccAddress;
}

public void setBccAddress(String[] bccAddress) {
this.bccAddress = bccAddress;
}

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getEncoding() {
return encoding;
}

public void setEncoding(String encoding) {
this.encoding = encoding;
}

public String[] getAttachments() {
return attachments;
}

public void setAttachments(String[] attachments) {
this.attachments = attachments;
}

public boolean isValidate() {
return validate;
}

public void setValidate(boolean validate) {
this.validate = validate;
}

public void setProperties(Properties properties) {
this.properties = properties;
}

}



参数:
email.server(邮件服务器信息):
mailServerHost=mail.renesola.com
mailServerPort=25
fromAddress=newsletter@renesola.com
username=newsletter
password=A1s2d3f4
encoding=utf-8
validate=false

email.user.register(用户邮箱注册):
<html><div id='mailContentContainer' style='font-size: 14px; padding: 0px; height: auto; margin-right: 170px;'>Dear Sir/Miss:<br><br> Thank you for registering Renesola, You only need to click on the following link to activate your account, you will be able to enjoy Renesola services.<br><br> <a target='_blank' href='http://test.renesola.com/theme/shop/_activationEmail.html?userid={userid}&email={email}' style=' color: #2a586f; text-decoration:underline!important;'>http://test.renesola.com/theme/shop/_activationEmail.html?userid={userid}&email={email}</a><br><br> (If you can not click on the URL link address, copy it and paste it into your browser's address input box, and then press Enter.)<br><br><br>With best regards,<br>Renesola.com</div><html>

email.user.forgetpassword(用户重置密码):
<html><div id='mailContentContainer' style='font-size: 14px; padding: 0px; height: auto; margin-right: 170px;'>Dear Sir/Miss:<br><br> Password reset successful.<br><br> new password: {password}<br><br> Please login to change your password as soon as possible.<br><br> <a target='_blank' href='http://test.renesola.com/theme/shop/login.jsp' style=' color: #2a586f; text-decoration:underline!important;'>http://test.renesola.com/theme/shop/login.jsp</a><br><br> (If you can not click on the URL link address, copy it and paste it into your browser's address input box, and then press Enter.)<br><br><br>With best regards,<br>Renesola.com</div><html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值