⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mialutil.txt

📁 带验证的javaMail邮件发送程序
💻 TXT
字号:
/*
 * Created on 2006-10-19
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author jpwang
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class MailUtil {
	
//	 Get system properties

	
	
	public static void main(String[] arg1){
	    //发送email
	    try {
	      //default account information
	      String smtpServer = ...;//邮件服务器
	      String smtpAuth = "true";//是否要验证
	      String smtpUser = ....;//发件人账号
	      String smtpPassword = ....;//密码
	      String From = ....;//发件人邮箱
	      String To = ....;//收件人
	      String Subject = ...;主题
	      String Text = "这是一个测试";
	      
	      Properties props = new Properties();
	      Session sendMailSession;
	      Transport transport;
	      props.put("mail.smtp.host", smtpServer);
	      props.put("mail.smtp.auth", smtpAuth);
	      if ("true".equals(smtpAuth)) {
	        //smtp服务器需要验证,用MyAuthertiactor来创建mail session
	        MyAuthenticator myauth = new MyAuthenticator(smtpUser, smtpPassword);
	        sendMailSession = Session.getInstance(props, myauth);
	      }
	      else {
	        sendMailSession = Session.getInstance(props);
	      }
	      //Debug
	      sendMailSession.setDebug(true);
	      Message newMessage = new MimeMessage(sendMailSession);
	      newMessage.setFrom(new InternetAddress(From));
	      newMessage.setRecipient(Message.RecipientType.TO,
	                              new InternetAddress(To));
	      newMessage.setSubject(Subject);
	      newMessage.setSentDate(new Date());
	      newMessage.setText(Text);
	      newMessage.saveChanges();
	      transport = sendMailSession.getTransport("smtp");
	      transport.send(newMessage, newMessage.getAllRecipients());
	      transport.close();
	    }
	    catch (Exception mailEx) {
	      System.err.println("Send Mail Error:" + mailEx.getMessage());
	     
	    }
	    
	  }
}
	  //smtp需要验证时候的验证类
 class MyAuthenticator
	      extends javax.mail.Authenticator {
	    private String strUser;
	    private String strPwd;
	    public MyAuthenticator(String user, String password) {
	      this.strUser = user;
	      this.strPwd = password;
	    }

	    protected PasswordAuthentication getPasswordAuthentication() {
	      return new PasswordAuthentication(strUser, strPwd);
	    }
	      }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -