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

java实现邮件发送

2011-06-10 21:14 615 查看
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class MailService {

/** 发信人 */
private String from;
/** 收信人 */
private String to;
/** 主题 */
private String subject;
/** 正文 */
private String body;

public MailService() {

}
/**
* 发送邮件.
* @return boolean - 发送结果
*/
public boolean sendMail() {
if (getBody() == null || getTo() == null || getFrom() == null
|| getSubject() == null) { return false; }
try {
Properties props = new Properties();
props.put("username", "xxx");
props.put("password", "xxxx");
props.put("mail.transport.protocol", "smtp" );
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.port", "25" );

Session mailSession = Session.getDefaultInstance(props);
Message msg = new MimeMessage(mailSession);

msg.setFrom(new InternetAddress(getFrom()));
msg.addRecipients(Message.RecipientType.TO, InternetAddress
.parse(getTo()));
msg.setSentDate(new Date());
msg.setSubject(getSubject());

msg.setText(getBody());
msg.saveChanges();
System.out.println("正在连接服务器。。。。");
Transport transport = mailSession.getTransport("smtp");
transport.connect(props.getProperty("mail.smtp.host"), props
.getProperty("username"), props.getProperty("password"));

System.out.println("正在发送邮件。。。。");
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("发送完毕。。。。");

} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
return false;
}
return true;
}

/**
* @return Returns the body.
*/
public String getBody() {
return body;
}

/**
* @param body
*            The body to set.
*/
public void setBody(String body) {
this.body = body;
}

/**
* @return Returns the from.
*/
public String getFrom() {
return from;
}

/**
* @param from
*            The from to set.
*/
public void setFrom(String from) {
this.from = from;
}

/**
* @return Returns the subject.
*/
public String getSubject() {
return subject;
}

/**
* @param subject
*            The subject to set.
*/
public void setSubject(String subject) {
this.subject = subject;
}

/**
* @return Returns the to.
*/
public String getTo() {
return to;
}

/**
* @param to
*            The to to set.
*/
public void setTo(String to) {
this.to = to;
}

public static void main(String[] args) {
MailService sender = new MailService();
sender.setFrom("xxxx@163.com");
sender.setTo("xxx@126.com");
sender.setSubject("测试邮件");
sender.setBody("测试邮件发送成功!");
sender.sendMail();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: