java web 发送邮件


写的不错的文章:


http://blog.csdn.net/conglinyu/article/details/56676848


===================================


只需修改web.xml 改为自己的即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用JavaMail API来发送带附件的电子邮件。以下是一个示例代码,展示了如何使用Java Servlet发送带附件的邮件: ```java import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; // 邮件服务器的配置信息 final String username = "[email protected]"; final String password = "your_email_password"; final String smtpHost = "smtp.example.com"; final int smtpPort = 587; // 发件人和收件人的电子邮件地址 String fromEmail = "[email protected]"; String toEmail = "[email protected]"; // 创建一个会话对象 Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", smtpPort); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // 创建一个默认的MimeMessage对象 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(fromEmail)); // 设置收件人 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail)); // 设置主题 message.setSubject("邮件主题"); // 创建一个Multipart对象,用于存储邮件的各个部分 Multipart multipart = new MimeMultipart(); // 创建邮件正文部分 BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("邮件正文"); multipart.addBodyPart(messageBodyPart); // 创建附件部分 messageBodyPart = new MimeBodyPart(); String filename = "path_to_attachment_file"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // 将Multipart对象设置为邮件内容 message.setContent(multipart); // 发送邮件 Transport.send(message); System.out.println("邮件发送成功"); } catch (MessagingException e) { e.printStackTrace(); } ``` 请将代码中的 `[email protected]`,`your_email_password`,`smtp.example.com`,`[email protected]`,`[email protected]` 和 `path_to_attachment_file` 替换为你自己的实际信息。 这段代码使用了JavaMail API来创建一个MimeMessage对象,并设置了发件人、收件人、主题和邮件正文。然后,创建了一个Multipart对象,并向其中添加了邮件正文部分和附件部分。最后,将Multipart对象设置为邮件内容,通过Transport类的send()方法发送邮件。 确保你的项目中包含了JavaMail API的相关依赖,并在Servlet的web.xml文件中配置好Servlet的映射和相关参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值