......................................................................
1条回答 默认 最新
- Robot-L 2015-12-17 10:52关注
//发送邮件
try {
Properties prop = new Properties();
//设置服务器地址
prop.put("mail.smtp.host", "smtp.qq.com");
//设置需要身份验证
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.connectiontimeout",Integer.parseInt(10) );//超时时间
//创建会话
Session session = Session.getDefaultInstance(prop);
session.setDebug(true);
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//设置发件人
// 给消息对象设置发件人
message.setFrom(new InternetAddress("aaaaaa"));//邮件前缀
//设置收件人
//toAddresss是一个字符串数组,存放收件人邮箱
if(toAddress.length>0){
InternetAddress[] to_mail=new InternetAddress[toAddress.length];
for(int i=0;i<toAddress.length;i++){
buffer.append(toAddress[i]);
to_mail[i]=new InternetAddress(toAddress[i]);
}
//记录日志
log.info("开始向"+buffer.toString()+"发送邮件!");
message.setRecipients(Message.RecipientType.BCC,to_mail);
}else{
return false;
}
//设置邮件主题
if(title!=null&&!title.equals("")){
message.setSubject(title);//邮件主题
}else{
return false;
}
//新建一个MimeMultipart对象来存放多个BodyPart对象
Multipart mul = new MimeMultipart();
//新建一个存放信件内容的BodyPart对象
BodyPart mdp = new MimeBodyPart();
mdp.setContent(content, "text/html;charset=UTF-8");
//将含有信件内容的BodyPart加入到MimeMulitipart对象中
mul.addBodyPart(mdp);
//添加附件
if (attachment!=null &&!attachment.equals("") ){//当存在附件时
// 设置信件的附件(用本机上的文件作为附件)
try {
mdp = new MimeBodyPart(); // 新建一个存放附件的BodyPart
// 此处需要转码,否则附件中包括中文时,将产生乱码
String adjunctname = new String(attachment.getBytes("UTF-8"), "UTF-8");
FileDataSource fds = new FileDataSource(附件内容);
DataHandler handler = new DataHandler(fds);
mdp.setFileName(adjunctname);
mdp.setDataHandler(handler);
mul.addBodyPart(mdp);
} catch (Exception e) {
log.error("向"+buffer.toString()+"发送邮件时获取邮件附件失败!");
}
}
//把mul作为消息对象的内容
message.setContent(mul);
message.saveChanges();
Transport transport = session.getTransport("SMTP");
//以smtp方式登录邮箱,第1个参数是发送邮件用的邮件服务器SMTP地址,第2个参数为用户名,第3个参数为密码
transport.connect(server,Integer.parseInt(protocol_port), user_account, user_passwd);
//发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
//日志
if (log.isInfoEnabled())
log.info("已向用户"+sender_address.toString()+"发送邮件["+title+"],内容["+content+"]");
} catch (Exception e) {
flag=false;
log.error("向"+buffer.toString()+"发送邮件失败!");
throw new RuntimeException("邮件发送失败!");
}
return flag;
}
//修改下就可以了解决 无用评论 打赏 举报
悬赏问题
- ¥15 stata安慰剂检验作图但是真实值不出现在图上
- ¥15 c程序不知道为什么得不到结果
- ¥40 复杂的限制性的商函数处理
- ¥15 程序不包含适用于入口点的静态Main方法
- ¥15 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
- ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
- ¥20 有关区间dp的问题求解
- ¥15 多电路系统共用电源的串扰问题