JavaMail保存为草稿邮件(只适合imap不适合pop3)

               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();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/xiao__jia__jia/article/details/83720509