既然是使用javamail的api,自然要导入一些jar到工程中,需要导入mail.jar,activition.jar
不多说,直接上代码
写了一个MailUtils.java
public class MainUtils {private int port = 25; //smtp协议使用的是25号端口private String server; // 发件人邮件服务器private String user; // 使用者账号private String password; //使用者密码//构造发送邮件帐户的服务器,端口,帐户,密码public MainUtils(String server, int port, String user, String passwd) {this.port = port;this.user = user;this.password = passwd;this.server = server;}/*** email 手机人电子邮箱* subject 邮件标题* body 正文内容* paths 发送的附件路径集合**/ public void sendEmail(String email, String subject, String body,List<String> paths) {Properties props = new Properties();props.put("mail.smtp.host", server);props.put("mail.smtp.port", String.valueOf(port));props.put("mail.smtp.auth", "true");Transport transport = null;Session session = Session.getDefaultInstance(props, null);MimeMessage msg = new MimeMessage(session);try {transport = session.getTransport("smtp");transport.connect(server, user, password); //建立与服务器连接msg.setSentDate(new Date()); InternetAddress fromAddress = null;fromAddress = new InternetAddress(user);msg.setFrom(fromAddress);InternetAddress[] toAddress = new InternetAddress[1];toAddress[0] = new InternetAddress(email);msg.setRecipients(Message.RecipientType.TO, toAddress);msg.setSubject(subject, "UTF-8"); //设置邮件标题MimeMultipart multi = new MimeMultipart(); //代表整个邮件邮件BodyPart textBodyPart = new MimeBodyPart(); //设置正文对象textBodyPart.setText(body); //设置正文multi.addBodyPart(textBodyPart); //添加正文到邮件for (String path: fileList) {FileDataSource fds = new FileDataSource(fileInfo.absolutePath); //获取磁盘文件BodyPart fileBodyPart = new MimeBodyPart(); //创建BodyPartfileBodyPart.setDataHandler(new DataHandler(fds)); //将文件信息封装至BodyPart对象String fileNameNew = MimeUtility.encodeText(fds.getName(),"utf-8", null); //设置文件名称显示编码,解决乱码问题fileBodyPart.setFileName(fileNameNew); //设置邮件中显示的附件文件名multi.addBodyPart(fileBodyPart); //将附件添加到邮件中}msg.setContent(multi); //将整个邮件添加到message中msg.saveChanges();transport.sendMessage(msg, msg.getAllRecipients()); //发送邮件transport.close();} catch (NoSuchProviderException e) {e.printStackTrace();} catch (MessagingException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}}}
再附一些常用的邮件服务器
126邮箱
POP3服务器:pop.126.com SMTP服务器:smtp.126.com
163邮箱
POP3服务器:pop.163.com SMTP服务器:smtp.163.com
yahoo邮箱
POP3服务器:pop.mail.yahoo.com.cn SMTP服务器:smtp.mail.yahoo.com.cn
Sohu邮箱
POP3服务器:pop3.sohu.com SMTP服务器:smtp.sohu.com
Gmail邮箱
POP3服务器是pop.gmail.com SMTP服务器是smtp.gmail.com
QQ邮箱
POP3服务器:pop.qq.com SMTP服务器:smtp.qq.com