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

java smtp发送邮件

2013-08-14 16:25 387 查看
public String sendPostbox(){
//获得属性,并生成Session对象
PostboxSite postboxSite = this.postboxManager.getPostboxSiteByMail(this.sendBoxForm.getFromUserName());
try {
Properties props = new Properties();
Session sendsession;
Transport transport;
sendsession = Session.getInstance(props, null);
//向属性中写入SMTP服务器的地址
props.put("mail.smtp.host", "smtp."+"163.com");
//设置SMTP服务器需要权限认证
props.put("mail.smtp.auth","true");
//设置输出调试信息
sendsession.setDebug(true);
//根据Session生成Message对象
Message message = new MimeMessage(sendsession);
//设置发信人地址
message.setFrom(new InternetAddress("xxxxxx@163.com"));
//设置收信人地址
message.setRecipient(Message.RecipientType.TO,new InternetAddress("xxxxxxxx@qq.com"));
//设置e-mail标题
message.setSubject("aabbccdd");
//设置e-mail发送时间
message.setSentDate(new Date());
//设置e-mail内容
message.setText("youjian");
//获得attachment参数
String attachment = new String("");
if (!attachment.equals(""))
{
}else{
//如无附件,则按纯文本格式处理
message.setText(new String("我的第一封邮件"));
}
//保存对于e-mail的修改
message.saveChanges();
//根据Session生成Transport对象
transport=sendsession.getTransport("smtp");
//连接到SMTP服务器
transport.connect("smtp."+"163.com","xxxxx","xxxxxx");//smtp服务器,邮箱用户名,邮箱密码
//发送e-mail
transport.sendMessage(message,message.getAllRecipients());
//关闭Transport连接
transport.close();
//保存发送的邮件信息
SendBox sendBox = new SendBox();
sendBox.setMailTitle(this.sendBoxForm.getMailTitle());
sendBox.setToUserNames(this.sendBoxForm.getToUserNames());
sendBox.setFromUserName(this.sendBoxForm.getFromUserName());
sendBox.setMailContent(this.sendBoxForm.getMailContent());

} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
ActionContext ctx = ActionContext.getContext();
ctx.put(WebConstants.STRUTS_SUBMIT_KEY, Boolean.TRUE);
return WebConstants.ACTION_SUCCESS_KEY;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: