Java发送邮件(带附件)

实现java发送邮件的过程大体有以下几步:

  1. 准备一个properties文件,该文件中存放SMTP服务器地址等参数。
  2. 利用properties创建一个Session对象
  3. 利用Session创建Message对象,然后设置邮件主题和正文
  4. 利用Transport对象发送邮件

需要的jar有2个:activation.jar和mail.jar

直接看个demo代码

#----------------这两个是构建session必须的字段----------
#smtp服务器
mail.smtp.host=smtp.qq.com
#身份验证
mail.smtp.auth=true
#--------------------------------------------------------------#发送者的邮箱用户名
mail.sender.username=xxx@xx.com
#发送者的邮箱密码
mail.sender.password=xxxxxxxxxxMailServer.properties
View Code

下面是发送邮件的java代码

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;public class JavaMail {/*** Message对象将存储我们实际发送的电子邮件信息,* Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail session。*/private MimeMessage message;/*** Session类代表JavaMail中的一个邮件会话。* 每一个基于JavaMail的应用程序至少有一个Session(可以有任意多的Session)。* * JavaMail需要Properties来创建一个session对象。* 寻找"mail.smtp.host"    属性值就是发送邮件的主机* 寻找"mail.smtp.auth"    身份验证,目前免费邮件服务器都需要这一项*/private Session session;/**** 邮件是既可以被发送也可以被受到。JavaMail使用了两个不同的类来完成这两个功能:Transport 和 Store。 * Transport 是用来发送信息的,而Store用来收信。对于这的教程我们只需要用到Transport对象。*/private Transport transport;private String mailHost="";private String sender_username="";private String sender_password="";private Properties properties = new Properties();/** 初始化方法*/public JavaMail(boolean debug) {InputStream in = JavaMail.class.getResourceAsStream("MailServer.properties");try {properties.load(in);this.mailHost = properties.getProperty("mail.smtp.host");this.sender_username = properties.getProperty("mail.sender.username");this.sender_password = properties.getProperty("mail.sender.password");} catch (IOException e) {e.printStackTrace();}session = Session.getInstance(properties);session.setDebug(debug);//开启后有调试信息message = new MimeMessage(session);}/*** 发送邮件* * @param subject*            邮件主题* @param sendHtml*            邮件内容* @param receiveUser*            收件人地址*/public void doSendHtmlEmail(String subject, String sendHtml,String receiveUser) {try {// 发件人//InternetAddress from = new InternetAddress(sender_username);// 下面这个是设置发送人的Nick nameInternetAddress from = new InternetAddress(MimeUtility.encodeWord("幻影")+" <"+sender_username+">");message.setFrom(from);// 收件人InternetAddress to = new InternetAddress(receiveUser);message.setRecipient(Message.RecipientType.TO, to);//还可以有CC、BCC// 邮件主题
            message.setSubject(subject);String content = sendHtml.toString();// 邮件内容,也可以使纯文本"text/plain"message.setContent(content, "text/html;charset=UTF-8");// 保存邮件
            message.saveChanges();transport = session.getTransport("smtp");// smtp验证,就是你用来发邮件的邮箱用户名密码
            transport.connect(mailHost, sender_username, sender_password);// 发送
            transport.sendMessage(message, message.getAllRecipients());//System.out.println("send success!");} catch (Exception e) {e.printStackTrace();}finally {if(transport!=null){try {transport.close();} catch (MessagingException e) {e.printStackTrace();}}}}public static void main(String[] args) {JavaMail se = new JavaMail(false);se.doSendHtmlEmail("邮件主题", "邮件内容", "xxx@XX.com");}
}
View Code

上面只能实现文本的发送,如果我们要发送附件,就需要用到Multipart对象了。

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;public class JavaMailWithAttachment {private MimeMessage message;private Session session;private Transport transport;private String mailHost = "";private String sender_username = "";private String sender_password = "";private Properties properties = new Properties();/** 初始化方法*/public JavaMailWithAttachment(boolean debug) {InputStream in = JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties");try {properties.load(in);this.mailHost = properties.getProperty("mail.smtp.host");this.sender_username = properties.getProperty("mail.sender.username");this.sender_password = properties.getProperty("mail.sender.password");} catch (IOException e) {e.printStackTrace();}session = Session.getInstance(properties);session.setDebug(debug);// 开启后有调试信息message = new MimeMessage(session);}/*** 发送邮件* * @param subject*            邮件主题* @param sendHtml*            邮件内容* @param receiveUser*            收件人地址* @param attachment*            附件*/public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {try {// 发件人InternetAddress from = new InternetAddress(sender_username);message.setFrom(from);// 收件人InternetAddress to = new InternetAddress(receiveUser);message.setRecipient(Message.RecipientType.TO, to);// 邮件主题
            message.setSubject(subject);// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件Multipart multipart = new MimeMultipart();// 添加邮件正文BodyPart contentPart = new MimeBodyPart();contentPart.setContent(sendHtml, "text/html;charset=UTF-8");multipart.addBodyPart(contentPart);// 添加附件的内容if (attachment != null) {BodyPart attachmentBodyPart = new MimeBodyPart();DataSource source = new FileDataSource(attachment);attachmentBodyPart.setDataHandler(new DataHandler(source));// 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();//messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");//MimeUtility.encodeWord可以避免文件名乱码
                attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));multipart.addBodyPart(attachmentBodyPart);}// 将multipart对象放到message中
            message.setContent(multipart);// 保存邮件
            message.saveChanges();transport = session.getTransport("smtp");// smtp验证,就是你用来发邮件的邮箱用户名密码
            transport.connect(mailHost, sender_username, sender_password);// 发送
            transport.sendMessage(message, message.getAllRecipients());System.out.println("send success!");} catch (Exception e) {e.printStackTrace();} finally {if (transport != null) {try {transport.close();} catch (MessagingException e) {e.printStackTrace();}}}}public static void main(String[] args) {JavaMailWithAttachment se = new JavaMailWithAttachment(true);File affix = new File("c:\\测试-test.txt");se.doSendHtmlEmail("邮件主题", "邮件内容", "xxx@XXX.com", affix);//
    }
}带附件
View Code

来源:https://www.cnblogs.com/yejg1212/archive/2013/06/01/3112702.html

 

转载于:https://www.cnblogs.com/tiankafei/p/10340643.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/278366.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

google天气预报接口_将天气预报添加到谷歌浏览器

google天气预报接口Are you looking for a quick and easy way to see your local weather forecast in Google Chrome? Then you will definitely want to take a good look at the AccuWeather Forecast extension. 您是否正在寻找一种快速简便的方法来在Google Chrome浏览器…

hive中任意相邻时间段数据获取

通过sql语句获取相邻时段数据不比通过其它编程语言&#xff0c;因为sql里面没有for循环&#xff0c;故在实现时需要增加一份副表数据&#xff0c;这里对该方法做一个记录。背景&#xff1a;获取2017年全年平台用户进出贵州省的次数&#xff08;分为进港次数和出港次数&#xff…

在谷歌浏览器中自动翻译文本

Do you need a quick and simple way to understand an unfamiliar language while browsing the Internet? Then join us as we take a look at the Auto-Translate extension for Google Chrome. 您需要一种快速简单的方法来浏览Internet时理解一种陌生的语言吗&#xff1f;…

知识点025-服务器的基础优化脚本

2019独角兽企业重金招聘Python工程师标准>>> 脚本是借鉴老男孩培训机构的&#xff0c; 感谢感谢~ mkdir -p /server/scripts cat >> /server/scripts/env.sh <<END #!/bin/bash #author Xiongchao #qq 704816384 #mail 704816384qq.com #selinux off…

微服务实现事务一致性实例

分布式系统架构中&#xff0c;分布式事务问题是一个绕不过去的挑战。而微服务架构的流行&#xff0c;让分布式事问题日益突出&#xff01; 下面我们以电商购物支付流程中&#xff0c;在各大参与者系统中可能会遇到分布式事务问题的场景进行详细的分析&#xff01; 如上图所示&a…

使用ama0实现串口通信_“ AMA”是什么意思,以及如何使用它?

使用ama0实现串口通信BigTunaOnline/ShutterstockBigTunaOnline / ShutterstockThe term “AMA” is a staple of Reddit, and it has spread to the far corners of the internet. But what does AMA mean, who came up with the word, and how do you use it? “ AMA”一词是…

火狐 url 乱码_在Firefox中查看URL作为工具提示

火狐 url 乱码Would you like a way to view link URLs wherever you mouse is located in a webpage rather than using the Status Bar? Now you can do so very easily with the URL Tooltip extension for Firefox. 您是否想通过一种方式而不是使用状态栏来查看链接URL&am…

java虚拟机之内存分配

Java 的自动内存管理主要是针对对象内存的回收和对象内存的分配。同时&#xff0c;Java 自动内存管理最核心的功能是 堆 内存中对象的分配与回收。 JDK1.8之前的堆内存示意图&#xff1a; 从上图可以看出堆内存分为新生代、老年代和永久代。新生代又被进一步分为&#xff1a;Ed…

知道无人驾驶的网络安全有多重要吗?英国政府都决定插手开发了

这样的策略也被解读为&#xff0c;英国政府希望借此抢占未来无人驾驶汽车研发的先机。 相信看过下午我们有关速8中黑科技的文章的朋友们&#xff0c;一定对有关车辆网络安全印象深刻&#xff0c;也足以见得未来无人驾驶时代的网络安全问题有多重要。所以&#xff0c;英国政府决…

linux uniq命令_如何在Linux上使用uniq命令

linux uniq命令Fatmawati Achmad Zaenuri/ShutterstockFatmawati Achmad Zaenuri / ShutterstockThe Linux uniq command whips through your text files looking for unique or duplicate lines. In this guide, we cover its versatility and features, as well as how you c…

win10任务栏和开始菜单_如何将网站固定到Windows 10任务栏或开始菜单

win10任务栏和开始菜单Having quick access to frequently-used or hard to remember websites can save you time and frustration. Whether you use Chrome, Firefox, or Edge, you can add a shortcut to any site right to your Windows 10 taskbar or Start menu. 快速访问…

WEB_矛盾

题目链接&#xff1a;http://123.206.87.240:8002/get/index1.php 题解&#xff1a; 打开题目&#xff0c;看题目信息&#xff0c;本题首先要弄清楚 is_numeric() 函数的作用 作用如下图&#xff1a; 即想要输出flag&#xff0c;num既不能是数字字符&#xff0c;不能为数1&…

如何在Windows上解决蓝牙问题

Bluetooth gives you the freedom to move without a tether, but it isn’t always the most reliable way to use wireless devices. If you’re having trouble with Bluetooth on your Windows machine, you can follow the steps below to troubleshoot it. 蓝牙使您可以不…

Multicast注册中心

1234提供方启动时广播自己的地址。   消费方启动时广播订阅请求。   提供方收到订阅请求时&#xff0c;单播自己的地址给订阅者&#xff0c;如果设置了unicastfalse&#xff0c;则广播给订阅者。   消费方收到提供方地址时&#xff0c;连接该地址进行RPC调用。 <du…

美味奇缘_轻松访问和管理您的美味书签

美味奇缘Looking for an easy way to access and manage your Delicious Bookmarks collection with minimal UI impact? Now you can with SimpleDelicious for Firefox. 是否正在寻找一种简单的方法来访问和管理您的Delicious Bookmarks收藏&#xff0c;而对UI的影响最小&am…

谈谈如何使用Netty开发实现高性能的RPC服务器

RPC&#xff08;Remote Procedure Call Protocol&#xff09;远程过程调用协议&#xff0c;它是一种通过网络&#xff0c;从远程计算机程序上请求服务&#xff0c;而不必了解底层网络技术的协议。说的再直白一点&#xff0c;就是客户端在不必知道调用细节的前提之下&#xff0c…

寒假万恶之源3:抓老鼠啊~亏了还是赚了?

1.代码&#xff1a; #include<iostream>using namespace std;int main(){ char a/*操作*/; int i/*计数工具*/,b0/*老鼠会开心几天*/; int e/*正常的来*/,f/*老鼠会悲伤几天*/; int c1/*老鼠来不来*/,d0/*奶酪数目*/,g0/*老鼠数目*/; for (i1;;i) { …

在Firefox中结合Wolfram Alpha和Google搜索结果

Do you wish there was a way to combine all that Wolfram Alpha and Google goodness together when you search for something? Now you can with the Wolfram Alpha Google extension for Firefox. 您是否希望有一种方法可以在搜索某些内容时将Wolfram Alpha和Google的所有…

kompozer如何启动_使用KompoZer创建网站

kompozer如何启动Are you looking for a way to easily start creating your own webpages? KompoZer is a nice basic website editor that will allow you to quickly get started and become familiar with the process. 您是否正在寻找一种轻松创建自己的网页的方法&#…

电脑pin重置_如果忘记了如何重置Windows PIN

电脑pin重置A good password or PIN is difficult to crack but can be difficult to remember. If you forgot or lost your Windows login PIN, you won’t be able to retrieve it, but you can change it. Here’s how. 好的密码或PIN很难破解&#xff0c;但很难记住。 如果…