import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailUtility {
private static int port = 25;
private String server = "mail.163.com";//邮件服务器
private String from = "vivk";//发送者,显示的发件人名字
private String user = "";//发送者邮箱地址
private String password = "";//密码
/**
* Send emails
* @param email
* @param subject
* @param body
* @throws UnsupportedEncodingException
*/
public void sendEmail(String [] email, String subject, String body) throws UnsupportedEncodingException {
try
{
Properties props = new Properties();
props.put("mail.smtp.host", server);
props.put("mail.smtp.port", String.valueOf(port));
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.starttls.enable", "true");
Transport transport = null;
Session session = Session.getInstance(props, new MailAuthenticator(from, password));
transport = session.getTransport("smtp");
transport.connect(server, user, password);
MimeMessage msg = new MimeMessage(session);
msg.setSentDate(new Date());
InternetAddress fromAddress = new InternetAddress(user,from,"UTF-8");
msg.setFrom(fromAddress);
InternetAddress[] toAddress = new InternetAddress[email.length];
for (int i=0;i<email.length;i++)
{
toAddress[i] = new InternetAddress(email[i]);
}
msg.setRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.saveChanges();
transport.sendMessage(msg, msg.getAllRecipients());
System.out.println("Complete sent emai!!!");
LogUtil.debug("Complete sent emai!!!");
}
catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
* 需要认证账号和密码
* @author zhaohongbing
*
*/
class MailAuthenticator extends Authenticator {
String user;
String pw;
public MailAuthenticator (String username, String password){
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user, pw);
}
}
public static void main(String args[]) throws UnsupportedEncodingException
{
EmailUtility myEmailUtility = new EmailUtility();
String [] toAddress = {"ans@163.com"};
myEmailUtility.sendEmail(toAddress,"邮件测试","测试邮件,收到请回复我一下,thanks");//收件人
}
}
相关文章
- 09-07Delphi发送邮件...
- 09-07Python——SMTP发送邮件
- 09-07使用Python SMTP发送邮件
- 09-07python通过SMTP发送邮件失败,报错505/535
- 09-07python实现邮件发送完整代码(带附件发送方式)
- 09-07Jenkins配置QQ邮箱发送邮件
- 09-07利用smtp协议实现黑窗口发送邮件
- 09-07.net core 个人 smtp服务 邮件发送
- 09-07如何优雅地定时发送QQ邮件“问候“别人
- 09-07邮件发送