大家好:有谁有关于java自动发送邮件的程序啊,关于jmail的实现。跪求啊。。。谢谢大家了啊。我的邮箱1020104799@qq.com
希望大家帮助我一下啊 !!!!!
------解决方案--------------------
jmail的用法度娘一搜一大堆
自动运行一般两种做法,一个是quartz,定时执行任务
一个是windows的计划任务或者linux的crontab
------解决方案--------------------
- Java code
import java.io.File;import java.util.Date;import java.util.Properties;import java.util.Vector;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Authenticator;import javax.mail.Multipart;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.internet.MimeUtility;public class SendMailTest { public int sendMail(String host, String from, String username, String password, String to, String subject, String content, Vector appendFiles, boolean author) { try { Properties p = System.getProperties(); p.put("mail.smtp.host", host); p.put("mail.smtp.auth", author + ""); p.put("mail.smtp.localhost", "forceview"); Session session = Session.getDefaultInstance(p, new PopupAuthenticator(username, password)); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from));// 设置发送帐号 String[] tos = to.split(";"); InternetAddress[] sendTo = new InternetAddress[tos.length]; for (int i = 0; i < tos.length; i++) { sendTo[i] = new InternetAddress(tos[i]); } msg.setRecipients(javax.mail.internet.MimeMessage.RecipientType.TO, sendTo);// 设置接收邮件的地址 msg.setSubject(subject, "utf-8");// 设置主题 msg.setSentDate(new Date());// 设置发送时间 Multipart mp = new MimeMultipart(); MimeBodyPart bp = new MimeBodyPart(); bp.setContent( "<meta http-equiv=Content-Type content=text/html; charset=utf-8>" + content, "text/html;charset=UTF-8"); mp.addBodyPart(bp); MimeBodyPart fp; String appendStrs = ""; if (appendFiles != null) { for (int i = 0; i < appendFiles.size(); i++) { fp = new MimeBodyPart(); appendStrs = appendFiles.get(i).toString(); String[] filenames = appendStrs.split("\\|"); if (new File(filenames[0]).exists()) { FileDataSource fds = new FileDataSource(filenames[0]); fp.setDataHandler(new DataHandler(fds)); fp.setFileName(MimeUtility.encodeText(filenames[1] + fds.getName(), "utf-8", "K")); mp.addBodyPart(fp); } } } msg.setContent(mp); msg.saveChanges(); Transport transport = session.getTransport("smtp");// 设置发送端口 transport.connect(host, username, password);// 连接邮件服务器 transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); return -1; } return 0; } class PopupAuthenticator extends Authenticator { private String username, password; public PopupAuthenticator(String username, String password) { this.username = username; this.password = password; } public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(this.username, this.password); } }}