您的位置:首页 > 编程语言 > Java开发

Java发送邮件

2008-08-01 18:09 399 查看
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dcampus;

import java.util.Properties;
import javax.mail.Message;
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;

/**
*发送邮件测试通过
* @author He Jianfei
*/
public class JavaMail {

private String host;
private String from;
private String to;
private String subject;
private String content;
private boolean authentication;
private String username;
private String password;

public void sendMail(String host, String from, String to, String subject,
String content, boolean authentication, String username,
String password) throws MessagingException {
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
if (!authentication) {
props.put("mail.smtp.auth", "false");
} else {
props.put("mail.smtp.auth", "true");
}
// Get session
Session session = Session.getDefaultInstance(props, null);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setContent(content, "text/html;charset=gb2312");
// Send message
if (authentication) {
Transport smtp = null;
try {
smtp = session.getTransport("smtp");
smtp.connect(host, username, password);
smtp.sendMessage(message, message.getAllRecipients());
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
smtp.close();
}
} else {
Transport.send(message);
}
}

public void send() throws MessagingException {
host = "smtp.scut.edu.cn";
from = "junwang@scut.edu.cn";
to = "wj_526@sina.com";
subject = "just for test";
content = "Beijing Olympic";
authentication = true;
username = "xxxxxxxx";
password = "xxxxxx";
sendMail(host, from, to, subject, content, authentication, username, password);
}

public static void main(String args[]) throws MessagingException {
JavaMail jm = new JavaMail();
jm.send();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: