公司遇到的一个问题,当设备达到警戒值的时候给客户邮箱发送邮件,及时处理设备故障。
于是我就网上搜索如何java发送邮件。
现在整理完毕,供大家参考。
现在的程序支持126 163等邮箱验证后给其他邮箱发邮件,但是QQ邮箱登录无法通过,请悉之。
于是我就网上搜索如何java发送邮件。
现在整理完毕,供大家参考。
现在的程序支持126 163等邮箱验证后给其他邮箱发邮件,但是QQ邮箱登录无法通过,请悉之。
理论上建立项目,导入jar包,把下面的内容复制到你的类里,然后改改配置(帐号密码,收件人),即可完成邮件发送。
如有问题可与本人联系。QQ:690726200
package com.xiao.email;
import java.security.Security;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email {
//收件人地址,内容
public static String send_email(String toaddress,String content){
String emailname="***@163.com"; //用户,此处未测试成功QQ的
String password="***";//密码
String smtpHostName = "smtp." + emailname.split("@")[1];
Properties props = System.getProperties();
// Properties props = new Properties();
props.setProperty("mail.smtp.host", smtpHostName);// 设置smtp服务器
props.put("mail.smtp.auth", "true");// 现在的大部分smpt都需要验证了
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.port", 25);
// Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// props.put("mail.smtp.starttls.enable", "true");
/* props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
props.put("mail.transport.protocal", "smtps");
props.put("mail.smtp.STARTTLS.enable", "true");
props.put("mail.smtps.**ssl.enable", "false");*/
// props.setProperty("mail.smtps.**ssl.required", "true");
Session s = Session.getInstance(props);// 为了查看运行时的信息
s.setDebug(true);
MimeMessage message = new MimeMessage(s);// 由邮件会话新建一个消息对象
try {
InternetAddress from = new InternetAddress(emailname);// 发件人
message.setFrom(from);
InternetAddress to = new InternetAddress(toaddress);// 收件人
message.setRecipient(Message.RecipientType.TO, to);
// 邮件标题
message.setSubject("通知消息");
//String content = email;// 邮件内容,也可以使纯文本"text/plain"
message.setContent(content, "textml;charset=utf-8");
/****下面代码是发送附件******
String fileName = "d://hello.txt";
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Hi");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileName);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);*/
message.saveChanges();
Transport transport = s.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(smtpHostName, emailname, password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return content;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
send_email("***@126.com","你好,前轴承报警,请及时查看。");//收件邮箱可以任意
}
}