JavaMail 发送 gmail 邮件

需要两个jar包

 

mail.javahttp://java.sun.com/products/javamail/downloads/index.html   ,其中包括mail.jar和文档
Activation.jarhttp://java.sun.com/products/javabeans/jaf/downloads/index.html ,其中包括Activation.jar

 

附件中亦含有

 

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class TestEmail {
	public void SendEmailTest() {
		Properties props = new Properties();
		props.setProperty("mail.smtp.host", "smtp.gmail.com");
		props.setProperty("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.port", "465");
		props.put("mail.smtp.auth", "true");
		Session sendMailSession = Session.getInstance(props, null);

		try {
			Transport transport = sendMailSession.getTransport("smtp");
			transport.connect("smtp.gmail.com", "[email protected]",
					"XXXX");
			Message newMessage = new MimeMessage(sendMailSession);

			//设置mail主题  
			String mail_subject = "更改邮件发送人测试";
			newMessage.setSubject(mail_subject);

			//设置发信人地址  
			String strFrom = "[email protected]";
			newMessage.setFrom(new InternetAddress(strFrom));
			//Address addressFrom[] = { new InternetAddress("[email protected]"),new InternetAddress("[email protected]") };
			//改变发件人地址
			//newMessage.addFrom(addressFrom);
			//设置收件人地址
			Address addressTo[] = { new InternetAddress("[email protected]") };
			newMessage.setRecipients(Message.RecipientType.TO, addressTo);

			//设置mail正文  
			newMessage.setSentDate(new java.util.Date());
			String mail_text = "更改邮件发件人调试成功!";
			newMessage.setText(mail_text);

			newMessage.saveChanges(); //保存发送信息  
			transport.sendMessage(newMessage, newMessage
					.getRecipients(Message.RecipientType.TO)); //发送邮件  

			transport.close();
			System.out.println("OK");
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	public static void main(String args[]) throws Exception {
		TestEmail SEmail = new TestEmail();
		SEmail.SendEmailTest();
	}
}

 

PS:如果所连接的邮箱没有开启SMTP的话是连不上去的,例如126/163 邮箱

你可能感兴趣的:(java,html,.net,sun,Gmail)