邮件发送,暂时只测试了QQ邮箱

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 发送普通邮件,接受普通邮件 发送带有附件的邮件,接收带有附件的邮件 发送html形式的邮件,接受html形式的邮件 发送带有图片的邮件等做了一个总结。
 */
public class Test {
	 static int port=25;
	 static String server="smtp.qq.com";
	 static String from="****@qq.com";
	 static String user="****";
	 static String password="******";
	 
	 public static void main(String[] args)
	 {
		 sendEmail("***@foxmail.com", "test", "test");
	 }
	 
	 public static void sendEmail(String email,String subject,String body){
	  try{
	   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;
	   MyAuthenticator myauth = new MyAuthenticator(from, password);
	   Session session=Session.getDefaultInstance(props,myauth);
	   session.setDebug(true);
	   transport=session.getTransport("smtp");
	   transport.connect(server,user,password);
	   MimeMessage msg=new MimeMessage(session);
	   msg.setSentDate(new Date());
	   InternetAddress fromAddress=new InternetAddress(from);
	   msg.setFrom(fromAddress);
	   InternetAddress[] toAddress=new InternetAddress[1];
	   toAddress[0]=new InternetAddress(email);
	   msg.setRecipients(Message.RecipientType.TO,toAddress);
	   msg.setSubject(subject);
	   msg.setText(body);
	   msg.saveChanges();
	   transport.sendMessage(msg,msg.getAllRecipients());//System.out.print("ok");
	   //Transport.send(msg);
	  }catch(NoSuchProviderException e){
	   e.printStackTrace();
	  }catch(MessagingException e){
	   e.printStackTrace();
	  }
	 }
	}
	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);
	 }
	}
 

 

你可能感兴趣的:(邮件发送)