JavaMail儲存為草稿郵件(只適合imap不適合pop3)
阿新 • • 發佈:2018-11-09
JavaMail儲存為草稿郵件(只適合imap不適合pop3)
轉載:https://blog.csdn.net/u013183865/article/details/40507145?locationNum=1&fps=1
import java.util.Date; import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class SaveDraf { public static String host = "******"; // 發件伺服器 public static String username = "*****";//郵箱賬戶 public static String password = "****";//密碼 public static void main(String[] args) { sendMail("收件郵箱", "郵件主題", "<h1>嗚哈哈哈哈</h1>"); } /** * @param to 收件人 * @param title 主題 * @param content 內容 */ public static void sendMail(String to, String title, String content) { Properties props = System.getProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Properties prop = new Properties(); Session session1 = Session.getDefaultInstance(prop, null); Store store = session1.getStore("imap"); store.connect(host, username, password); Folder folder = store.getFolder("Drafts");// 開啟草稿箱 MimeMessage mmessage = new MimeMessage(session); mmessage.setFrom(new InternetAddress(username)); mmessage.setRecipient(Message.RecipientType.TO,new InternetAddress(to)); mmessage.setSubject(title); Multipart mainPart = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(content, "text/html; charset=utf-8"); mainPart.addBodyPart(html); mmessage.setContent(mainPart); mmessage.setSentDate(new Date()); mmessage.saveChanges(); mmessage.setFlag(Flags.Flag.DRAFT, true); MimeMessage draftMessages[] = {mmessage}; System.out.println(mmessage.getSubject()); folder.appendMessages(draftMessages); // Transport.send(mmessage); System.out.println("儲存成功"); } catch (Exception ex) { ex.printStackTrace(); } } }