java mail Demo

本文提供了一段使用Java发送邮件的代码示例,详细解释了如何配置邮件服务器、设置邮件参数、添加附件和正文内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public void toSendMail() throws MessagingException, IOException{
  Properties props = new Properties();
  props.setProperty("mail.smtp.auth", "true");
  props.setProperty("mail.transport.protocol", "smtp");
  props.setProperty("mail.host", "smtp.sina.com");
  Session session = Session.getInstance(props,new Authenticator(){
   @Override
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("zhoujiaqiang3684","******");
   }
  });
  session.setDebug(true);
  
  Message msg = new MimeMessage(session);
  msg.setFrom(new InternetAddress(" zhoujiaqiang3684@sina.com"));
  msg.setRecipients(RecipientType.TO, InternetAddress.parse(" 271626270@qq.com,646698721@qq.com"));
  msg.setSubject("测试邮件");
  //内容部分分为附件和正文,两者为并列关系
  MimeMultipart msgMultipart = new MimeMultipart("mixed");
  //附件部分
  MimeBodyPart attch = new MimeBodyPart();
  attch.attachFile("G:/测试.txt");
  attch.setFileName(MimeUtility.encodeText("测试.txt"));
  //正文部分
  MimeBodyPart con = new MimeBodyPart();
  
  //正文包括文本和图片,两者为依赖关系
  MimeMultipart  contentMultipart= new MimeMultipart("related");
  //img部分
  MimeBodyPart img = new MimeBodyPart();
  img.attachFile("G:/logo.jpg");
  img.setHeader("Content-Location", " http://www.baidu.com/img/baidu_sylogo1.gif");
  //html部分
  MimeBodyPart html = new MimeBodyPart();
  html.setContent("<img src='http://www.baidu.com/img/baidu_sylogo1.gif'>你好:<br>这是一封<font color='red' size='6'>测试邮件!!</font>", "text/html;charset=gbk");
  
  //将附件和正文添加到内容当中
  msgMultipart.addBodyPart(attch);
  msgMultipart.addBodyPart(con);
  //将文本和图片添加到正文当中
  contentMultipart.addBodyPart(html);
  contentMultipart.addBodyPart(img);
  //
  con.setContent(contentMultipart);
  //将内容添加到消息当中
  msg.setContent(msgMultipart);
  
  Transport.send(msg);
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值