阅读背景:

发送邮件email(smtp)

来源:互联网 
package test.NetworkProgramming;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Scanner;

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

public class MailSender {
	// 有关smtp的配置放在mail.properties	
//mail.transport.protocol= smtps
//mail.smtps.auth=true
//mail.smtps.host=smtp.gmail.com
//[email protected]
	
	String propfileName = "mail.properties";
	// 邮件放在mail.txt
	String mailfileName = "mail.txt";
	String user = "[email protected]";
	String password = "3031103929";
	@SuppressWarnings("static-access")
	public  void sendMail() throws IOException, AddressException, MessagingException{
		Properties properties = new Properties();
		InputStream inputStream = new FileInputStream(new File(propfileName));
		properties.load(inputStream);
		
		Scanner in = new Scanner(new FileInputStream(new File(mailfileName)));
		String from = in.nextLine();
		String to = in.nextLine();
		String subject = in.nextLine();
		StringBuilder text = new StringBuilder();
		while(in.hasNextLine()) {
			text.append(in.nextLine());
			text.append("\n");
		}
		//创建一个会话用于发送邮件
		Session mailSession = Session.getDefaultInstance(properties);
		//使用message来封装一个邮件
		MimeMessage message = new MimeMessage(mailSession);
		message.setFrom(new InternetAddress(from));
		message.addRecipient(RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);
		message.setText(text.toString());
		
		//使用transport来发送邮件。  在会话session下开始传输transport一个邮件message
		Transport transport = mailSession.getTransport();
		try {
			transport.connect();
			transport.send(message,message.getAllRecipients());
		}finally {
			transport.close();
		}
		
	}
	public static void main(String args[]) throws AddressException, IOException, MessagingException {
		new MailSender().sendMail();
	}
}
package test.NetworkProgramming;

import java.i



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: