Java如何发邮件

先准备好需要的jar包 javamail包 activation包

下载地址:

https://cid-f38f3771ea144ff2.office.live.com/self.aspx/.Documents/mail.jar

https://cid-f38f3771ea144ff2.office.live.com/self.aspx/.Documents/activation.jar

代码如下:

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mail {
	public static void main(String[] args) {

		Properties props = System.getProperties();

		// 设置smtp服务器
		props.setProperty("mail.smtp.host", "mailhost");

		// 现在的大部分smpt都需要验证了
		props.put("mail.smtp.auth", "true");

		Session s = Session.getInstance(props);

		// 为了查看运行时的信息
		s.setDebug(true);

		// 由邮件会话新建一个消息对象
		MimeMessage message = new MimeMessage(s);

		try {
			// 发件人
			InternetAddress from = new InternetAddress(
					"问题儿童@博客园.com");
			message.setFrom(from);

			// 收件人
			InternetAddress to = new InternetAddress("问题儿童@博客园.com");
			message.setRecipient(Message.RecipientType.TO, to);

			// 邮件标题
			message.setSubject("测试");
			String content = "测试内容";

			// 邮件内容,也可以使纯文本"text/plain"
			message.setContent(content, "text/html;charset=GBK");

			/****
			 * 下面代码是发送附件****** String fileName = "C:\\helloworld.txt"; MimeBodyPart
			 * messageBodyPart = new MimeBodyPart();
			 * messageBodyPart.setText("Hi"); Multipart multipart = new
			 * MimeMultipart(); multipart.addBodyPart(messageBodyPart);
			 * 
			 * messageBodyPart = new MimeBodyPart(); DataSource source = new
			 * FileDataSource(fileName); messageBodyPart.setDataHandler(new
			 * DataHandler(source)); messageBodyPart.setFileName(fileName);
			 * multipart.addBodyPart(messageBodyPart);
			 * 
			 * message.setContent(multipart);
			 */

			message.saveChanges();
			Transport transport = s.getTransport("smtp");

			// smtp验证,就是你用来发邮件的邮箱用户名密码
			transport.connect("mailhost", "问题儿童", "123456");

			// 发送
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

如果发给多人,这只要把收件人那里的代码修改如下:

String to[]={"a@163.com","b@163.com"};

// getMailList是对多个地址的处理方法
String toList = getMailList(to);

InternetAddress[] iaToList = new InternetAddress().parse(toList);

// 收件人
msg.setRecipients(Message.RecipientType.TO,iaToList);

getMailList方法的代码如下:

private String getMailList(String[] mailArray){

	StringBuffer toList = new StringBuffer();

	int length = mailArray.length;
	if(mailArray!=null && length <2) {
		toList.append(mailArray[0]);
	} else {
			for(int i=0;i<length;i++){
				toList.append(mailArray[i]);
				if(i!=(length-1)){
				toList.append(",");
			}
		}
	 }

	 return toList.toString();
}

posted on 2011-03-15 16:35  問題兒童  阅读(2273)  评论(0)    收藏  举报

导航