import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
public class A {
public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
reSendEmail();
}
public static void reSendEmail() throws MessagingException, UnsupportedEncodingException {
String host="smtp.mxhichina.com";//服务器(这是阿狸的可以更换为eg:腾讯qq等)
String password="123456";//邮箱密码
String from="123.com";//邮箱用户名
String email ="1185365895.com";//手机人邮箱地址
//发送邮件;
MimeMessageHelper messageHelper = null;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setDefaultEncoding("UTF-8");
mailSender.setJavaMailProperties(props);
mailSender.setPassword(password);
mailSender.setPort(25);
mailSender.setSession(session);
mailSender.setUsername(from);
MimeMessage createMimeMessage = mailSender.createMimeMessage();
messageHelper = new MimeMessageHelper(createMimeMessage, true, "UTF-8");
messageHelper.setFrom(new InternetAddress(from, "测试邮件", "UTF-8"));
messageHelper.setTo(email);
messageHelper.setSubject("邮件主题");
/*File file = new File(email.getEmailPath());
String fileNm = file.getName();
messageHelper.addAttachment(fileNm, file);*/
messageHelper.setText("邮件内容", true);
mailSender.send(createMimeMessage);
}
}
如果host;password;form配置不对会报526;535等错
Caused by: javax.mail.AuthenticationFailedException: 526 Authentication failure[0]
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
at javax.mail.Service.connect(Service.java:295)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:421)
... 4 more
在这里有一些配置:
如何设置IMAP、POP3/SMTP及其SSL加密方式?
具体设置可以看:http://service.exmail.qq.com/cgi-bin/help?id=28&no=1000585&subtype=1