java发送邮件及邮件附件代码实例
java发邮件(word2003)
今天做了一个java发送邮件的小例子,总结一下,愿意和大家交换意见。
相关内容:1、要有两个邮箱(一个发送邮件,一个接收邮件)2、下载两个jar包(mail-1.4.1.jar,activation-1.1.1.jar)3、编写一个发送邮件的类(SendMail)原理:程序利用发送邮件的账号(这里是a123456@和密码999999)去登录邮箱服务器(这里是)。
之后向另外一个邮箱(这里是123456@)发送一个邮件,邮件的标题和内容等可以在程序里面设定好以下代码可以正确运行且发送邮件。
注意修改两个邮箱地址import java.util.Properties;import javax.mail.BodyPart;import javax.mail.Message;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;public class SendMail {private String host= ""; // smtp服务器 ,这里是网易126 邮箱服务器地址private String user = "a123456"; // 用户名,即发送邮件邮箱(a123456@)的名称private String pwd= "999999"; // 密码,a123456@ 在 的登录密码private String from = "a123456@"; // 发件人地址private String to = "123456@"; // 收件人地址private String subject = "hello"; // 邮件标题public void setAddress(String from, String to, String subject) { this.from = from;this.to = to;this.subject = subject;}/***此方法可以不做修改,直接调用*@param txt*/public void send(String txt) {Properties props = new Properties();// 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)props.put("mail.smtp.host", host);// 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)props.put("mail.smtp.auth", "true");// 用刚刚设置好的props对象构建一个sessionSession session = Session.getDefaultInstance(props);// 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使// 用(你可以在控制台(console)上看到发送邮件的过程)session.setDebug(true);// 用session为参数定义消息对象MimeMessage message = new MimeMessage(session);try {// 加载发件人地址message.setFrom(new InternetAddress(from));// 加载收件人地址message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// 加载标题message.setSubject(subject);// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 Multipart multipart = new MimeMultipart();// 设置邮件的文本内容BodyPart contentPart = new MimeBodyPart();contentPart.setText(txt);multipart.addBodyPart(contentPart);// 添加附件//BodyPart messageBodyPart = new MimeBodyPart();//DataSource source = new FileDataSource(affix);// 添加附件的内容//messageBodyPart.setDataHandler(newDataHandler(source));// 添加附件的标题// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码//sun.misc.BASE64Encoder enc = newsun.misc.BASE64Encoder();//messageBodyPart.setFileName("=?GBK?B?"+enc.encode(affixName.getBytes()) + "?=");//multipart.addBodyPart(messageBodyPart);// 将multipart对象放到message中message.setContent(multipart);// 保存邮件message.saveChanges();// 发送邮件Transport transport = session.getTransport("smtp");// 连接服务器的邮箱transport.connect(host, user, pwd);// 把邮件发送出去transport.sendMessage(message,message.getAllRecipients());transport.close();} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {SendMail cn = new SendMail();// 设置发件人地址、收件人地址和邮件标题cn.setAddress("a123456@", "123456@", "helloss");cn.send("hello余云峰");}}注意会出现:1、如果出现Exception in thread "main" ng.NoClassDefFoundError:com/sun/mail/util/BASE64EncoderStream解决办法:下载mail.jar包,添加到lib里就可以了~2、如果你用myEclipse进行开发的话,运行时可能会出现以下的错误:Exception in thread "main" ng.NoClassDefFoundError:com/sun/mail/util/LineInputStream解决方法:移除myEclipse自带的Java EE 5 Libraries包。
Java实现发送邮件并携带附件
Java实现发送邮件并携带附件本⽂实例为⼤家分享了Java实现发送邮件并携带附件的具体代码,供⼤家参考,具体内容如下⼀、邮件服务器与传输协议要在⽹络上实现邮件功能,必须要有专门的邮件服务器。
主要负责接收⽤户投递过来的邮件,并把邮件投递到邮件接收者的电⼦邮箱中。
SMTP服务器地址:⼀般是 ,163邮箱是,qq邮箱是。
SMTP协议通常把处理⽤户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)。
POP3协议通常把处理⽤户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)。
⼆、在发送⼈邮箱中开启POP3/SMTP服务qq邮箱登录qq邮箱后→设置→账户→ POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务→ POP3/SMTP服务点击开启(需要绑定⼿机号发送验证短信)→获得了⼀串授权码(后续发送邮件需要)163邮箱登录163邮箱→设置→ POP3/SMTP/IMAP → POP3/SMTP服务点击开启(需要邮箱app认证)→获取到⼀串授权码三、导⼊依赖<dependency><groupId>javax.mail</groupId><artifactId>mail</artifactId><version>1.5.0-b01</version></dependency>四、编写⼯具类import lombok.extern.slf4j.Slf4j;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.*;import java.util.Date;import java.util.Properties;@Slf4jpublic class EmailUtils {public static final String SenderEmail = "xxxxx@";//发送⼈邮箱public static final String senderCode = "ixxxxxxxxxxxdcd";//发送⼈邮箱授权码public static final String emailSMTPHost = "";//服务器地址public static final String receiveMailAccount = "xxxxx@";//收件⼈邮箱public static final String ccMailAccount = "xxxxx@";//抄送⼈邮箱public static final String bccmailAccount = "xxxxxx@";//密送⼈邮箱/*发送邮件*/public static void sendMail() {try {Properties props = new Properties();props.setProperty("mail.transport.protocol", "smtp");// 使⽤的协议props.setProperty("mail.smtp.host", emailSMTPHost);// 发件⼈的邮箱的SMTP服务器地址props.setProperty("mail.smtp.auth", "true");// 需要请求认证Session session = Session.getInstance(props);//得到会话对象实例session.setDebug(false);//是否打印详细⽇志MimeMessage message = createMimeMessage(session);//获取邮件对象(封装了⼀个⽅法)Transport transport = session.getTransport();transport.connect(SenderEmail, senderCode);//连接发送⼈的邮箱账户// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件⼈, 抄送⼈, 密送⼈transport.sendMessage(message, message.getAllRecipients());// 7. 关闭连接transport.close();("邮件发送成功");} catch (Exception e) {log.error("发送邮件失败");}}public static MimeMessage createMimeMessage(Session session) throws Exception {// 1. 创建⼀封邮件MimeMessage message = new MimeMessage(session);// 2. From: 发件⼈message.setFrom(new InternetAddress(SenderEmail, "发件⼈", "UTF-8"));// 3. 设置收件⼈、抄送⼈、密送⼈//MimeMessage.RecipientType.TO:收件类型;:抄送类型;MimeMessage.RecipientType.BCC:密送类型 message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailAccount, "收件⼈", "UTF-8"));message.setRecipient(, new InternetAddress(ccMailAccount, "抄送⼈", "UTF-8"));message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(bccmailAccount, "密送⼈", "UTF-8"));// 4. Subject: 邮件主题message.setSubject("这是邮件的主题", "UTF-8");// 5. Content: 邮件正⽂(可以使⽤html标签)message.setContent("这是邮件正⽂", "text/html;charset=UTF-8");*****************以下部分为携带附件代码,不需要携带附件的可删除星号圈起的部分*************************MimeMultipart multipart = new MimeMultipart();MimeBodyPart file1 = new MimeBodyPart();DataHandler handler = new DataHandler(new FileDataSource("⽂件路径"));file1.setDataHandler(handler);//对⽂件名进⾏编码,防⽌出现乱码String fileName = MimeUtility.encodeWord("⽂件名", "utf-8", "B");file1.setFileName(fileName);multipart.addBodyPart(file1);message.setContent(multipart);*******************************************************************************************// 6. 设置发件时间message.setSentDate(new Date());// 7. 保存设置message.saveChanges();return message;}}五、最后在同时设置正⽂和附件时,导致发送邮件后正⽂不显⽰,请⼤佬们指点。
个人java邮件发送程序例子
/** 收件人地址 **/
private String email = null;
/** 标签对应的值(子类来引用这个变量), 格式为key:<OrderNO>, value:050500001 **/
protected Map map = null;
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
mapValue = "";
}
replaceStr = replaceStr.replaceAll(label[i], mapValue);
}
程序基本情况“
需要发的信件有 发货通知,订单确认信,订单取消信等等,我建立一个保存jsp模版的数据表,字段主要有ID(主键),TITLE(邮件主题),BODY(邮件内容),BODY设置为CLOB类型,其实是各种信件的jsp页面,上面有若干标签,如:<OrderNO>,<MemberName>(每种模版标签都不一样),发送之前选出邮件数据,并逐条把这些标签替换掉,然后调用邮件发送类SendMail.send(LetterTemplate letter)来循环发送。
"<PaymentRemark>",
"<OrderNO>",
"<MemberEmail>",
"<MemberPostcode>",
"<MemberAddress>",
Java实现发送邮件,图片,附件
Java实现发送邮件,图⽚,附件1、JavaMail 介绍JavaMail 是sun公司(现以被甲⾻⽂收购)为⽅便Java开发⼈员在应⽤程序中实现邮件发送和接收功能⽽提供的⼀套标准开发包,它⽀持⼀些常⽤的邮件协议,如前⾯所讲的SMTP,POP3,IMAP,还有MIME等。
我们在使⽤JavaMail API 编写邮件时,⽆须考虑邮件的底层实现细节,只要调⽤JavaMail 开发包中相应的API类就可以了。
JavaMail 下载地址:2、JavaMail APIJavaMail API 按照功能可以划分为如下三⼤类:①、创建和解析邮件的API②、发送邮件的API③、接收邮件的API以上三种类型的API在JavaMail 中由多个类组成,但是主要有四个核⼼类,我们在编写程序时,记住这四个核⼼类,就很容易编写出Java邮件处理程序。
Message 类:javax.mail.Message 类是创建和解析邮件的核⼼ API,这是⼀个抽象类,通常使⽤它的⼦类javax.mail.internet.MimeMessage 类。
它的实例对象表⽰⼀份电⼦邮件。
客户端程序发送邮件时,⾸先使⽤创建邮件的 JavaMail API 创建出封装了邮件数据的 Message 对象,然后把这个对象传递给邮件发送API(Transport 类)发送。
客户端程序接收邮件时,邮件接收API把接收到的邮件数据封装在Message 类的实例中,客户端程序在使⽤邮件解析API从这个对象中解析收到的邮件数据。
Transport 类:javax.mail.Transport 类是发送邮件的核⼼API 类,它的实例对象代表实现了某个邮件发送协议的邮件发送对象,例如 SMTP 协议,客户端程序创建好Message 对象后,只需要使⽤邮件发送API 得到 Transport 对象,然后把 Message 对象传递给 Transport 对象,并调⽤它的发送⽅法,就可以把邮件发送给指定的 SMTP 服务器。
Java 发送邮件
使用Java应用程序发送E-mail 十分简单,但是首先你应该在你的机器上安装JavaMail API 和Java Activation Framework (JAF) 。
您可以从Java 网站下载最新版本的JavaMail,打开网页右侧有个Downloads 链接,点击它下载。
您可以从Java 网站下载最新版本的JAF(版本1.1.1)。
你也可以使用本站提供的下载链接:JavaMail mail.jar 1.4.5JAF(版本1.1.1)activation.jar下载并解压缩这些文件,在新创建的顶层目录中,您会发现这两个应用程序的一些jar 文件。
您需要把mail.jar 和activation.jar 文件添加到您的CLASSPATH 中。
如果你使用第三方邮件服务器如QQ的SMTP服务器,可查看文章底部用户认证完整的实例。
发送一封简单的E-mail下面是一个发送简单E-mail的例子。
假设你的本地主机已经连接到网络。
编译并运行这个程序来发送一封简单的E-mail:如果你想发送一封e-mail给多个收件人,那么使用下面的方法来指定多个收件人ID:下面是对于参数的描述:type:要被设置为TO, CC 或者BCC,这里CC 代表抄送、BCC 代表秘密抄送。
举例:Message.RecipientType.TOaddresses: 这是email ID 的数组。
在指定电子邮件ID 时,你将需要使用InternetAddress() 方法。
发送一封HTML E-mail下面是一个发送HTML E-mail 的例子。
假设你的本地主机已经连接到网络。
和上一个例子很相似,除了我们要使用setContent() 方法来通过第二个参数为"text/html",来设置内容来指定要发送HTML 内容。
编译并运行此程序来发送HTML e-mail:发送带有附件的E-mail下面是一个发送带有附件的E-mail的例子。
hutool mail用法
hutool mail用法Hutool Mail 详细使用指南简介Hutool Mail 是一个功能强大且易于使用的 Java 邮件发送工具。
它提供了发送简单文本邮件、HTML 邮件以及附件邮件等功能,可以满足各种场景下的邮件发送需求。
用法引入依赖首先,在项目的 `` 文件中添加以下依赖:<dependency><groupId></groupId><artifactId>hutool-mail</artifactId><version></version></dependency>发送简单文本邮件Hutool Mail 可以轻松地发送简单的文本邮件。
以下是发送简单文本邮件的示例代码:// 创建邮件配置MailAccount account = new MailAccount();("");(25);(true);("");("username");("password");// 创建邮件SimpleMail mail = new SimpleMail(account);("Hello Hutool Mail");(true);("This is a simple text email.");// 添加收件人("");// 发送邮件();发送 HTML 邮件Hutool Mail 还支持发送 HTML 邮件,可以发送富文本内容。
以下是发送 HTML 邮件的示例代码:// 创建邮件配置(同上述示例)// 创建邮件HtmlMail mail = new HtmlMail(account);("Hello Hutool Mail");(true);("<h1>This is a HTML email.</h1>");// 添加收件人(同上述示例)// 发送邮件(同上述示例)();发送带附件的邮件如果需要发送带附件的邮件,Hutool Mail 也提供了相应的功能。
javamail收发邮件(带附件,正文带图)
1.邮件1.1 邮件组成部分如果是新邮件就获取,并解析它;邮件是由邮件头和邮件体组成,在邮件头中主要包含了收件人、发件人、主题等等基础信息。
而邮件体中就包括了邮件的正文和附件等内容信息。
下图就是pop3协议下,邮件的大致内容。
1.2 发送邮件(带附件、正文带图片)QQ邮箱为例:需要QQ账号和QQ登录第三方客户端时,密码框的“授权码”(相当于密码)授权码如下获取:代码如下:public class JavaMailboxAttachment {private MimeMessage message;private Session session;private String mailHost = "";private String mailAuth = "";private String mailPort = "";private String sender_username = "";private String sender_password = "";//定义一个Properties 用于存放信息private Properties properties = new Properties();//-------------------------------发信箱---------------------------------------------public JavaMailboxAttachment(String email_type) {try {properties.put("mail.smtp.host",""); //发送邮件服务器//端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587properties.put("mail.smtp.port", "587"); //发送邮件端口号properties.put("mail.smtp.auth", "true");// 此处填写你的账号properties.put("er", "xxxxxxxxx@");// 此处的密码就是前面说的16位STMP授权码properties.put("mail.password", "xxxxxxxxxxxxxxxx");this.mailHost = properties.getProperty("mail.smtp.host");this.mailAuth = properties.getProperty("mail.smtp.auth");this.mailPort = properties.getProperty("mail.smtp.port");this.sender_username = properties.getProperty("er");this.sender_password = properties.getProperty("mail.password");} catch (Exception e) {e.printStackTrace();}// 构建授权信息,用于进行SMTP进行身份验证Authenticator authenticator = new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {// 用户名、密码String userName = properties.getProperty("er");String password = properties.getProperty("mail.password");return new PasswordAuthentication(userName, password);}};session = Session.getInstance(properties,authenticator); //用户验证message = new MimeMessage(session); //将验证成功的session信息,创建一个message 对象。
java邮件发送(单人,多人,抄送,Excel附件)
java邮件发送(单⼈,多⼈,抄送,Excel附件) 直接上代码保存吧package com.westvalley.ceiec.page.report.sendmail;import weaver.email.EmailEncoder;import javax.mail.*;import javax.mail.internet.*;import javax.mail.util.ByteArrayDataSource;import javax.activation.*;import mons.logging.Log;import mons.logging.LogFactory;import ermodel.HSSFWorkbook;import crivia.db.i.DataSet;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.util.*;/**邮件发送⼯具类* @author whh*/public class Email {Log log = LogFactory.getLog(this.getClass());//发件⼈地址private String mail_from;public void setMail_from(String mailFrom) {mail_from = mailFrom;}public String getMail_from() {return mail_from;}//发件⼈密码private String password;public void setPassword(String password) {this.password = password;}public String getPassword() {return password;}//收件地址private String mail_to;public void setMail_to(String mailTo) {mail_to = mailTo;}public String getMail_to() {return mail_to;}//主题private String title;public void setTitle(String title) {this.title = title;}public String getTitle() {return title;}//内容private String message;public void setMessage(String message) {this.message = message;}public String getMessage() {return message;}//发件⼈邮件服务器如: 191.0.0.6private String send_server;public void setSend_server(String sendServer) {send_server = sendServer;}public String getSend_server() {return send_server;}/** 单个发送 setMail_to(String mailTo)* @return是否正确发送* @throws AddressException*/public boolean SendMail()throws AddressException{try{int n = this.mail_from.indexOf('@');int m = this.mail_from.length();//取邮件的服务器String server = this.mail_from.substring(n+1, m);//建⽴邮件会话Properties pro = new Properties();pro.put("mail.smtp.host", "smtp."+server);pro.put("mail.smtp.auth", "true");Session sess = Session.getInstance(pro);sess.setDebug(true);//新建⼀个消息对象MimeMessage message = new MimeMessage(sess);//设置发件⼈InternetAddress from_address = new InternetAddress(this.mail_from); message.setFrom(from_address);//设置收件⼈InternetAddress to_address = new InternetAddress(this.mail_to);message.setRecipient(Message.RecipientType.TO, to_address);//设置主题message.setSubject(title);//设置内容message.setContent(this.message, "text/html;charset=UTF-8");//设置发送时间message.setSentDate(new Date());//发送邮件message.saveChanges(); //保存邮件信息//设置发送的格式Transport transport = sess.getTransport("smtp");if(this.send_server == null){transport.connect("191.0.0.6", this.mail_from, password);}else{transport.connect(this.send_server, this.mail_from, password);}transport.sendMessage(message, message.getAllRecipients());transport.close();("向"+this.mail_to+"发送邮件成功");return true;}catch(Exception e){("发送邮件失败,原因可能是"+e.toString());return false;}}/**群发* @param addresses 地址list* @return* @throws AddressException*/public boolean SendMail(List<String> addresses) throws AddressException{ try{int n = this.mail_from.indexOf('@');int m = this.mail_from.length();//取邮件的服务器String server = this.mail_from.substring(n+1, m);//建⽴邮件会话Properties pro = new Properties();pro.put("mail.smtp.host", "smtp."+server);pro.put("mail.smtp.auth", "true");Session sess = Session.getInstance(pro);sess.setDebug(true);//新建⼀个消息对象MimeMessage message = new MimeMessage(sess);//设置发件⼈InternetAddress from_address = new InternetAddress(this.mail_from); message.setFrom(from_address);//设置收件⼈,多个final int num = addresses.size();InternetAddress to_address[] = new InternetAddress[num];for(int i=0; i<num; i++){to_address[i] = new InternetAddress(addresses.get(i));}message.setRecipients(Message.RecipientType.TO, to_address);//设置主题message.setSubject(title);//设置内容message.setContent(this.message, "text/html;charset=UTF-8");//设置发送时间message.setSentDate(new Date());//发送邮件message.saveChanges(); //保存邮件信息//设置发送的格式Transport transport = sess.getTransport("smtp");if(this.send_server == null){transport.connect("191.0.0.6", this.mail_from, password);}else{transport.connect(this.send_server, this.mail_from, password);}transport.sendMessage(message, message.getAllRecipients());transport.close();("发送邮件成功");return true;}catch(Exception e){("发送邮件失败,原因可能是"+e.getMessage());return false;}}/** 多⼈发送并抄送增加:2017-04-25 whh* @param addresses 收件邮箱(多个)* @param ccAddresses 抄送邮箱(多个)* @return* @throws AddressException*/public boolean SendMail(List<String> addresses, List<String> ccAddresses) throws AddressException{if(0==ccAddresses.size()){ //20170428 whhreturn SendMail(addresses);}try{int n = this.mail_from.indexOf('@');int m = this.mail_from.length();//取邮件的服务器String server = this.mail_from.substring(n+1, m);//建⽴邮件会话Properties pro = new Properties();pro.put("mail.smtp.host", "smtp."+server);pro.put("mail.smtp.auth", "true");Session sess = Session.getInstance(pro);sess.setDebug(true);//新建⼀个消息对象MimeMessage message = new MimeMessage(sess);//设置发件⼈InternetAddress from_address = new InternetAddress(this.mail_from);message.setFrom(from_address);//设置收件⼈,多个final int num = addresses.size();InternetAddress to_address[] = new InternetAddress[num];for(int i=0; i<num; i++){to_address[i] = new InternetAddress(addresses.get(i));}message.setRecipients(Message.RecipientType.TO, to_address);//设置抄送⼈final int ccSize = ccAddresses.size();if(ccSize > 0){InternetAddress cc_Address[] = new InternetAddress[ccSize];for(int i=0; i<ccSize; i++){cc_Address[i] = new InternetAddress(ccAddresses.get(i));}message.setRecipients(, cc_Address);}//设置主题message.setSubject(title);//设置内容message.setContent(this.message, "text/html;charset=UTF-8");//设置发送时间message.setSentDate(new Date());//发送邮件message.saveChanges(); //保存邮件信息//设置发送的格式Transport transport = sess.getTransport("smtp");if(this.send_server == null){transport.connect("191.0.0.6", this.mail_from, password);}else{transport.connect(this.send_server, this.mail_from, password);}transport.sendMessage(message, message.getAllRecipients());transport.close();("发送邮件成功");return true;}catch(Exception e){("发送邮件失败,原因可能是"+e.getMessage());return false;}}/** 多⼈发送并抄送增加:2019-06-14 whh* @param addresses 收件邮箱(多个)* @param ccAddresses 抄送邮箱(多个)* @param is 附件* @return* @throws AddressException*/public boolean SendMail(List<String> addresses, List<String> ccAddresses,HSSFWorkbook workBook,String workBookName) throwsAddressException{try{int n = this.mail_from.indexOf('@');int m = this.mail_from.length();//取邮件的服务器String server = this.mail_from.substring(n+1, m);//建⽴邮件会话Properties pro = new Properties();pro.put("mail.smtp.host", "smtp."+server);pro.put("mail.smtp.auth", "true");Session sess = Session.getInstance(pro);sess.setDebug(true);//新建⼀个消息对象MimeMessage message = new MimeMessage(sess);//设置发件⼈InternetAddress from_address = new InternetAddress(this.mail_from);message.setFrom(from_address);//设置收件⼈,多个final int num = addresses.size();InternetAddress to_address[] = new InternetAddress[num];for(int i=0; i<num; i++){to_address[i] = new InternetAddress(addresses.get(i));}message.setRecipients(Message.RecipientType.TO, to_address);//设置抄送⼈final int ccSize = ccAddresses.size();if(ccSize > 0){InternetAddress cc_Address[] = new InternetAddress[ccSize];for(int i=0; i<ccSize; i++){cc_Address[i] = new InternetAddress(ccAddresses.get(i));}message.setRecipients(, cc_Address);}//附件ByteArrayOutputStream baos = new ByteArrayOutputStream();workBook.write(baos);baos.flush();byte[] bt = baos.toByteArray();InputStream is = new ByteArrayInputStream(bt, 0, bt.length);baos.close();/*添加正⽂内容*/Multipart multipart = new MimeMultipart();BodyPart contentPart = new MimeBodyPart();// contentPart.setText(this.message);// contentPart.setHeader("Content-Type", "text/html;charset=UTF-8");contentPart.setContent(this.message, "text/html;charset=UTF-8");multipart.addBodyPart(contentPart);/*添加附件*/MimeBodyPart fileBody = new MimeBodyPart();DataSource source = new ByteArrayDataSource(is, "application/msexcel"); fileBody.setDataHandler(new DataHandler(source));// 中⽂乱码问题fileBody.setFileName(MimeUtility.encodeText(workBookName+".xls"));multipart.addBodyPart(fileBody);//设置主题message.setSubject(title);//设置内容message.setContent(multipart);//设置发送时间message.setSentDate(new Date());//发送邮件message.saveChanges(); //保存邮件信息//设置发送的格式Transport transport = sess.getTransport("smtp");if(this.send_server == null){transport.connect("191.0.0.6", this.mail_from, password);}else{transport.connect(this.send_server, this.mail_from, password);}transport.sendMessage(message, message.getAllRecipients());transport.close();("发送邮件成功");return true;}catch(Exception e){("发送邮件失败,原因可能是"+e.getMessage());return false;}}/**邮箱初始化,发件⼈邮箱、密码及服务器信息的获取* @return正确获取时返回Email对象,否则为null*/public static Email intiEmail(){// Log log = LogFactory.getLog(this.getClass());Email email = new Email();//获取系统的邮箱信息DataSet data = SQL.select(SQL.sql_Array(" select defmailpassword" +",defmailserver,defmailfrom from SystemSet "));if(data.next()){//发件⼈邮箱地址email.setMail_from(data.get("defmailfrom"));//获取并解析邮箱密码email.setPassword(EmailEncoder.DecoderPassword(data.get("defmailpassword")));// ("Password:"+EmailEncoder.DecoderPassword(data.get("defmailpassword"))); //服务器信息email.setSend_server(data.get("defmailserver"));}if(email.getMail_from().equals("")||email.getPassword().equals("")||email.getSend_server().equals("")){// ("发送⼈邮箱错误");// ("From:"+email.getMail_from()+"Password:"+// email.getPassword()+"Server:"+email.getSend_server());return null;}return email;}}。
java发送邮件及邮 件附件代码实例
Mail attachment = partSet.get(i);
String attachmentContent = attachment.getContent();
if (null != attachmentContent && 0 < attachmentContent.length()) {
*中查找其相应的MIME类型,如果没找到,则返回
* {@link #defaultAttachmentContentType}
*所指定的默认类型。
*
* @param fileName
*文件名
* @return返回文件对应的MIME类型。
*/
private String getPartContentType(String fileName) {
}
ret = contentTypeMap.get(fileName);
}
if (null == ret) {
ret = defaultAttachmentContentType;
}
return ret;
}
/**
*将给定字符串转换为base64编码的字符串
*
* @param str
*需要转码的字符串
contentTypeMap.put("doc", "application/msword");
contentTypeMap.put("dot", "application/msword");
contentTypeMap.put("docx", "application/msword");
javaemail发送邮件(带附件)
package com.send.email;import javax.mail.*;import javax.mail.internet.*;import java.util.*;import javax.activation.*;public class SendMail2 {private String host = ""; //smtp服务器private String from = ""; //发件人地址private String to = ""; //收件人地址private String affix = ""; //附件地址private String affixName = ""; //附件名称private String user = ""; //用户名private String pwd = ""; //密码private String subject = ""; //邮件标题public void setAddress(String from,String to,String subject){ this.from = from;this.to = to;this.subject = subject;}public void setAffix(String affix,String affixName){this.affix = affix;this.affixName = affixName;}public void send(String host,String user,String pwd) { this.host = host;er = user;this.pwd = pwd;Properties props = new Properties();//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)props.put("mail.smtp.host", host);//需要经过授权,也就是有户名和密码的校验,这样才能通过验证props.put("mail.smtp.auth", "true");//用刚刚设置好的props对象构建一个sessionSession session = Session.getDefaultInstance(props);//有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使//用(你可以在控制台(console)上看到发送邮件的过程)session.setDebug(true);//用session为参数定义消息对象MimeMessage message = new MimeMessage(session);try{//加载发件人地址message.setFrom(new InternetAddress(from));//加载收件人地址message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));//加载标题message.setSubject(subject);// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件Multipart multipart = new MimeMultipart();//设置邮件的文本内容BodyPart contentPart = new MimeBodyPart();contentPart.setText("第二种方法···");multipart.addBodyPart(contentPart);//添加附件BodyPart messageBodyPart= new MimeBodyPart();DataSource source = new FileDataSource(affix);//添加附件的内容messageBodyPart.setDataHandler(new DataHandler(source));//添加附件的标题//这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();messageBodyPart.setFileName("=?GBK?B?"+enc.encode(affixName.getBytes())+"?=");multipart.addBodyPart(messageBodyPart);//将multipart对象放到message中message.setContent(multipart);//保存邮件message.saveChanges();// 发送邮件Transport transport = session.getTransport("smtp");//连接服务器的邮箱transport.connect(host, user, pwd);//把邮件发送出去transport.sendMessage(message, message.getAllRecipients());transport.close();}catch(Exception e){e.printStackTrace();}}public static void main(String[] args){SendMail2 cn = new SendMail2();//设置发件人地址、收件人地址和邮件标题cn.setAddress("发件人地址","收件人的地址","一个带附件的JavaMail邮件(标题)"); //设置要发送附件的位置和标题cn.setAffix("附件的路径","文件名称");//设置smtp服务器以及邮箱的帐号和密码cn.send("","邮箱账号","密码");}}。
javaemail发送邮件(带附件)
private void getMailSet(){this.from = IConstants.MAIL_FROM;senderImpl = new JavaMailSenderImpl();senderImpl.setHost(IConstants.MAIL_HOST.trim());senderImpl.setUsername(IConstants.MAIL_USERNAME.trim());senderImpl.setPassword(IConstants.MAIL_PASSWORD.trim());Properties javaMailProperties = new Properties();javaMailProperties.put("mail.smtp.auth", "true");javaMailProperties.put("mail.smtp.timeout", "25000");senderImpl.setJavaMailProperties(javaMailProperties);}public void sendAffixMail(final String pdfUrl,final String pdfname,final String userEmail,final String username){taskExecutor.execute(new Runnable() {public void run() {try{getMailSet();seAffixMail(pdfUrl,pdfname,userEmail,username);}catch (Exception e) {e.printStackTrace();}}});}//发送附件public void seAffixMail(String pdfUrl,String pdfname,String userEmail,String username) throws MessagingException{try{//javaMail方式Mail mail = new Mail();mail.setSmtpServer(IConstants.MAIL_HOST.trim());//服务器mail.setUserName(IConstants.MAIL_USERNAME.trim());//账户mail.setPassword(IConstants.MAIL_PASSWORD.trim());//密码mail.setFrom(IConstants.MAIL_FROM.trim());//发件人账户mail.setDisplayName(IConstants.NICK);//显示发件人别名,如:楷誉金融<xxyin_vip@>mail.setTo(userEmail);//收件人mail.setIfAuth(true);//开启发送账户验证mail.addAttachfile(pdfUrl.trim());//添加附件mail.setSubject("电子协议"); //主题mail.setContent("尊敬的用户:"+username+"您投资借款成功,收到电子协议,请查收!");//内容HashMap map = mail.send();System.out.println("================="+map);}catch (Exception e) {e.printStackTrace();System.out.println("附件发送失败!");}}public class Mail {//定义发件人、收件人、SMTP服务器、用户名、密码、主题、内容等private String displayName;private String to;private String from;private String smtpServer;private String username;private String password;private String subject;private String content;private boolean ifAuth; //服务器是否要身份认证private String filename="";private Vector file = new Vector(); //用于保存发送附件的文件名的集合/*** 设置SMTP服务器地址*/public void setSmtpServer(String smtpServer){this.smtpServer=smtpServer;}/*** 设置发件人的地址*/public void setFrom(String from){this.from=from;}/*** 设置显示的名称*/public void setDisplayName(String displayName){this.displayName=displayName;}/*** 设置服务器是否需要身份认证*/public void setIfAuth(boolean ifAuth){ this.ifAuth=ifAuth;}/*** 设置E-mail用户名*/public void setUserName(String username){ ername=username;}/*** 设置E-mail密码*/public void setPassword(String password){ this.password=password;}/*** 设置接收者*/public void setTo(String to){this.to=to;}/*** 设置主题*/public void setSubject(String subject){ this.subject=subject;}/*** 设置主体内容*/public void setContent(String content){ this.content=content;}/*** 该方法用于收集附件名*/public void addAttachfile(String fname){file.addElement(fname);}//空构造器public Mail(){}/*** 初始化SMTP服务器地址、发送者E-mail地址、用户名、密码、接收者、主题、内容*/public Mail(String smtpServer,String from,String displayName,String username,String password,String to,String subject,String content){this.smtpServer=smtpServer;this.from=from;this.displayName=displayName;this.ifAuth=true;ername=username;this.password=password;this.to=to;this.subject=subject;this.content=content;}/*** 初始化SMTP服务器地址、发送者E-mail地址、接收者、主题、内容*/public Mail(String smtpServer,String from,String displayName,String to,String subject,String content){this.smtpServer=smtpServer;this.from=from;this.displayName=displayName;this.ifAuth=false;this.to=to;this.subject=subject;this.content=content;}/*** 发送邮件*/public HashMap send(){HashMap map=new HashMap();map.put("state", "success");String message="邮件发送成功!";Session session=null;Properties props = System.getProperties();props.put("mail.smtp.host", smtpServer);if(ifAuth){ //服务器需要身份认证props.put("mail.smtp.auth","true");SmtpAuth smtpAuth=new SmtpAuth(username,password);session=Session.getDefaultInstance(props, smtpAuth);}else{props.put("mail.smtp.auth","false");session=Session.getDefaultInstance(props, null);}//session.setDebug(true);Transport trans = null;try {Message msg = new MimeMessage(session);try{Address from_address = new InternetAddress(from, displayName);msg.setFrom(from_address);}catch(java.io.UnsupportedEncodingException e){e.printStackTrace();}InternetAddress[] address={new InternetAddress(to)};msg.setRecipients(Message.RecipientType.TO,address);msg.setSubject(subject);Multipart mp = new MimeMultipart();MimeBodyPart mbp = new MimeBodyPart();mbp.setContent(content.toString(),"text/html;charset=gb2312");mp.addBodyPart(mbp);if(!file.isEmpty()){//有附件Enumeration efile=file.elements();while(efile.hasMoreElements()){mbp=new MimeBodyPart();filename=efile.nextElement().toString(); //选择出每一个附件名FileDataSource fds=newFileDataSource(filename); //得到数据源mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPartmbp.setFileName(fds.getName()); //得到文件名同样至入BodyPartmp.addBodyPart(mbp);}file.removeAllElements();}msg.setContent(mp); //Multipart加入到信件msg.setSentDate(new Date()); //设置信件头的发送日期//发送信件msg.saveChanges();trans = session.getTransport("smtp");trans.connect(smtpServer, username, password);trans.sendMessage(msg, msg.getAllRecipients());trans.close();}catch(AuthenticationFailedException e){map.put("state", "failed");message="邮件发送失败!错误原因:\n"+"身份验证错误!";e.printStackTrace();}catch (MessagingException e) {message="邮件发送失败!错误原因:\n"+e.getMessage();map.put("state", "failed");e.printStackTrace();Exception ex = null;if ((ex = e.getNextException()) != null) { System.out.println(ex.toString());ex.printStackTrace();}}//System.out.println("\n提示信息:"+message);map.put("message", message);return map;}}。
发送邮件—java代码简单实例
1.准备jar包下载地址:/s/1bnF90Of提取密码:mopr修改环境变量编辑CLASSPA TH,在其后添加: %JA V A_HOME%\lib\mail.jar JAVA_HOME是jdk根目录,这里不做解释。
2.源代码//SendMail.javaimport java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.Message;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.Authenticator;import javax.mail.PasswordAuthentication;public class SendMail{public static void main(String [] args){String smtp = "";//smtp服务器String from = "888888@";//发件人String to = "100000@";//收件人String copyto = "200000@";//抄送String subject = "MailTest";//主题String content = "Hello,Java";//正文String username = "888888@";//发件人邮箱登录名String password = "123456";//发件人邮箱登录密码String filename = "test.text";//附件URLMail.sendAndCc(smtp,from,to,copyto,subject,content,username,password,filename);}}class Mail {private MimeMessage mimeMsg; //MIME邮件对象private Session session; //邮件会话对象private Properties props; //系统属性private boolean needAuth = false; //smtp是否需要认证//smtp认证用户名和密码private String username;private String password;private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象/*** Constructor* @param smtp 邮件发送服务器*/public Mail(String smtp){setSmtpHost(smtp);createMimeMessage();}/*** 设置邮件发送服务器* @param hostName String*/public void setSmtpHost(String hostName) {System.out.println("设置系统属性:mail.smtp.host = "+hostName);if(props == null)props = System.getProperties(); //获得系统属性对象props.put("mail.smtp.host",hostName); //设置SMTP主机}/*** 创建MIME邮件对象* @return*/public boolean createMimeMessage(){try {System.out.println("准备获取邮件会话对象!");session = Session.getDefaultInstance(props,null); //获得邮件会话对象}catch(Exception e){System.err.println("获取邮件会话对象时发生错误!"+e);return false;}System.out.println("准备创建MIME邮件对象!");try {mimeMsg = new MimeMessage(session); //创建MIME邮件对象mp = new MimeMultipart();return true;} catch(Exception e){System.err.println("创建MIME邮件对象失败!"+e);return false;}}/*** 设置SMTP是否需要验证* @param need*/public void setNeedAuth(boolean need) {System.out.println("设置smtp身份认证:mail.smtp.auth = "+need);if(props == null) props = System.getProperties();if(need){props.put("mail.smtp.auth","true");}else{props.put("mail.smtp.auth","false");}}/*** 设置用户名和密码* @param name* @param pass*/public void setNamePass(String name,String pass) {username = name;password = pass;}/*** 设置邮件主题* @param mailSubject* @return*/public boolean setSubject(String mailSubject) {System.out.println("设置邮件主题!");try{mimeMsg.setSubject(mailSubject);return true;}catch(Exception e) {System.err.println("设置邮件主题发生错误!");return false;}}/*** 设置邮件正文* @param mailBody String*/public boolean setBody(String mailBody) {try{BodyPart bp = new MimeBodyPart();bp.setContent(""+mailBody,"text/html;charset=GBK");mp.addBodyPart(bp);return true;} catch(Exception e){System.err.println("设置邮件正文时发生错误!"+e);return false;}}/*** 添加附件* @param filename String*/public boolean addFileAffix(String filename) {System.out.println("增加邮件附件:"+filename);try{BodyPart bp = new MimeBodyPart();FileDataSource fileds = new FileDataSource(filename);bp.setDataHandler(new DataHandler(fileds));bp.setFileName(fileds.getName());mp.addBodyPart(bp);return true;} catch(Exception e){System.err.println("增加邮件附件:"+filename+"发生错误!"+e);return false;}}/*** 设置发信人* @param from String*/public boolean setFrom(String from) {System.out.println("设置发信人!");try{mimeMsg.setFrom(new InternetAddress(from)); //设置发信人return true;} catch(Exception e) {return false;}}/*** 设置收信人* @param to String*/public boolean setTo(String to){if(to == null)return false;try{mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));return true;} catch(Exception e) {return false;}}/*** 设置抄送人* @param copyto String*/public boolean setCopyTo(String copyto){if(copyto == null)return false;try{mimeMsg.setRecipients(,(Address[])InternetAddress.parse(copyt o));return true;}catch(Exception e){ return false; }}/*** 发送邮件*/public boolean sendOut(){try{mimeMsg.setContent(mp);mimeMsg.saveChanges();System.out.println("正在发送邮件....");Session mailSession = Session.getInstance(props,null);//System.out.println("111111");Transport transport = mailSession.getTransport("smtp");//System.out.println("222222");transport.connect((String)props.get("mail.smtp.host"),username,password);//System.out.println("333333");transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));//System.out.println("444444");transport.sendMessage(mimeMsg,mimeMsg.getRecipients());//transport.send(mimeMsg);System.out.println("发送邮件成功!");transport.close();return true;} catch(Exception e) {System.err.println("邮件发送失败!"+e);return false;}}/*** 调用sendOut方法完成邮件发送* @param smtp* @param from* @param to* @param subject* @param content* @param username* @param password* @return boolean*/public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password) {Mail theMail = new Mail(smtp);theMail.setNeedAuth(true); //需要验证if(!theMail.setSubject(subject)) return false;if(!theMail.setBody(content)) return false;if(!theMail.setTo(to)) return false;if(!theMail.setFrom(from)) return false;theMail.setNamePass(username,password);if(!theMail.sendOut()) return false;return true;}* 调用sendOut方法完成邮件发送,带抄送* @param smtp* @param from* @param to* @param copyto* @param subject* @param content* @param username* @param password* @return boolean*/public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password) {Mail theMail = new Mail(smtp);theMail.setNeedAuth(true); //需要验证if(!theMail.setSubject(subject)) return false;if(!theMail.setBody(content)) return false;if(!theMail.setTo(to)) return false;if(!theMail.setCopyTo(copyto)) return false;if(!theMail.setFrom(from)) return false;theMail.setNamePass(username,password);if(!theMail.sendOut()) return false;return true;}/*** 调用sendOut方法完成邮件发送,带附件* @param smtp* @param from* @param to* @param subject* @param content* @param username* @param password* @param filename 附件路径* @return*/public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password,String filename) {Mail theMail = new Mail(smtp);theMail.setNeedAuth(true); //需要验证if(!theMail.setSubject(subject)) return false;if(!theMail.setBody(content)) return false;if(!theMail.addFileAffix(filename)) return false;if(!theMail.setTo(to)) return false;if(!theMail.setFrom(from)) return false;theMail.setNamePass(username,password);if(!theMail.sendOut()) return false;return true;}/*** 调用sendOut方法完成邮件发送,带附件和抄送* @param smtp* @param from* @param to* @param copyto* @param subject* @param content* @param username* @param password* @param filename* @return*/public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password,String filename) {Mail theMail = new Mail(smtp);theMail.setNeedAuth(true); //需要验证if(!theMail.setSubject(subject)) return false;if(!theMail.setBody(content)) return false;if(!theMail.addFileAffix(filename)) return false;if(!theMail.setTo(to)) return false;if(!theMail.setCopyTo(copyto)) return false;if(!theMail.setFrom(from)) return false;theMail.setNamePass(username,password);if(!theMail.sendOut()) return false;return true;}}。
java利用springJavaMailSenderImpl发送邮件,支持普通文本、附件、。。。
java利⽤springJavaMailSenderImpl发送邮件,⽀持普通⽂本、附件、。
博客分类:本⽂主要介绍利⽤发送邮件。
⾸先介绍了发送⼀般邮件,然后介绍了发送富⽂本(html)邮件及以velocity为模板发送邮件。
邮件发送分为为三步:创建邮件发送器、编写邮件、发送邮件。
Spring的提供了强⼤的邮件发送功能,可发送普通⽂本邮件、带附件邮件、html格式邮件、带图⽚邮件、设置发送内容编码格式、设置发送⼈的显⽰名称。
下⾯就进⾏介绍,⽰例代码中很多都是字符串硬编码,实际使⽤时推荐使⽤spring的配置⽂件进⾏配置。
1、创建邮件发送器⾸先定义对象,并对其进⾏smtp相关信息设置,相当于我们⾃⼰的邮箱,如下:Java代码1. JavaMailSenderImpl mailSender = new JavaMailSenderImpl();2. mailSender.setHost("");3. mailSender.setUsername("mosaic@");4. mailSender.setPassword("asterisks");JavaMailSenderImpl mailSender = new JavaMailSenderImpl();mailSender.setHost("");mailSender.setUsername("mosaic@");mailSender.setPassword("asterisks");当然更好的⽅法是使⽤配置⽂件进⾏配置,这⾥只是进⾏介绍,忽略硬编码先。
以上主机为邮箱服务商的smtp地址,⽤户名、密码为⽤户⾃⼰的邮箱。
除以上外还可以设置setPort(int port) 、setProtocol(String protocol) 等,可暂时不考虑。
JAVA发送邮件
以下是两种邮件发送方式。
给出的例子是是发送HTML格式带附件的邮件。
(普通文本格式的邮件基本上可以不关心,现在的邮件都是HTML格式的!)如果不要发送附件,只要发送单纯的HTML邮件。
只要把附件部分去掉即可Java代码1./**2.*用spring mail 发送邮件,依赖jar:spring.jar,activation.jar,mail.jar3.*/4.5.public static void sendFileMail() throws MessagingException {6. JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();7.8. // 设定mail server9. senderImpl.setHost("");10. senderImpl.setUsername("yuhan0");11. senderImpl.setPassword("******");12. // 建立HTML邮件消息13. MimeMessage mailMessage = senderImpl.createMimeMessage();14. // true表示开始附件模式15. MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");16.17. // 设置收件人,寄件人18. messageHelper.setTo("slimes@");19. messageHelper.setFrom("yuhan0@");20. messageHelper.setSubject("测试邮件!");21. // true 表示启动HTML格式的邮件22. messageHelper.setText("<html><head></head><body><h1>你好:附件!!</h1></body></html>", true);23.24. FileSystemResource file1 = new FileSystemResource(new File("d:/logo.jpg"));25. FileSystemResource file2 = new FileSystemResource(new File("d:/读书.txt"));26. // 添加2个附件27. messageHelper.addAttachment("logo.jpg", file1);28.29. try {30. //附件名有中文可能出现乱码31. messageHelper.addAttachment(MimeUtility.encodeWord("读书.txt"), file2);32. } catch (UnsupportedEncodingException e) {33. e.printStackTrace();34. throw new MessagingException();35. }36. // 发送邮件37. senderImpl.send(mailMessage);38. System.out.println("邮件发送成功.....");39.40. }41./***用apache commons-email 发送邮件*依赖jar:commons-email.jar,activation.jar,mail.jar*/public static void sendMutiMessage() {MultiPartEmail email = new MultiPartEmail();String[] multiPaths = new String[] { "D:/1.jpg", "D:/2.txt" };List<EmailAttachment> list = new ArrayList<EmailAttachment>();for (int j = 0; j < multiPaths.length; j++) {EmailAttachment attachment = new EmailAttachment();//判断当前这个文件路径是否在本地如果是:setPath 否则 setURL;if (multiPaths[j].indexOf("http") == -1) {attachment.setPath(multiPaths[j]);} else {try {attachment.setURL(new URL(multiPaths[j]));} catch (MalformedURLException e) {e.printStackTrace();}}attachment.setDisposition(EmailAttachment.ATTACHMENT);attachment.setDescription("Picture of John");list.add(attachment);}try {// 这里是发送服务器的名字:email.setHostName("");// 编码集的设置email.setCharset("utf-8");// 收件人的邮箱email.addTo("slimes@");// 发送人的邮箱email.setFrom("yuhan0@");// 如果需要认证信息的话,设置认证:用户名-密码。
Java实现网易企业邮箱发送邮件
Java实现⽹易企业邮箱发送邮件最近项⽬需要⽤⽹易企业邮箱发送邮件,特意来将实现过程记录⼀下:maven导⼊jar包1 <!-- javax.mai 核⼼包 -->2 <dependency>3 <groupId>javax.activation</groupId>4 <artifactId>activation</artifactId>5 <version>1.1</version>6 </dependency>7 <dependency>8 <groupId>javax.mail</groupId>9 <artifactId>mail</artifactId>10 <version>1.4.5</version>11 </dependency>java 使⽤ javax.mail 实现企业邮箱邮件发送1 import java.util.Properties;2 import javax.mail.internet.InternetAddress;3 import javax.mail.internet.MimeMessage;4 import javax.mail.internet.MimeUtility;5 import org.apache.log4j.Logger;6 import org.springframework.mail.javamail.JavaMailSenderImpl;7 import org.springframework.mail.javamail.MimeMessageHelper;8 import com.sun.mail.util.MailSSLSocketFactory;910public class SendMailSmtp {11private static Logger log = Logger.getLogger(SendTemplateSMS.class);1219public static void sendHtmlMail() {20try{21 String from = "邮箱账号名";//发件⼈昵称展⽰ *22 String[] to ={"接收邮箱1","接收邮箱2"};//接收邮箱23 String subject = "邮件主题";//邮件主题 *24 String text = "邮件内容";25 String host = "";//163企业邮箱smtp *26 String username = "发件的企业邮箱";//企业邮箱 *27 String password= "发件的企业邮箱的授权码";//企业邮箱密码 *2829//设置服务器验证信息30 Properties prop = new Properties();31 prop.setProperty("mail.smtp.auth", "true");32 prop.setProperty("mail.smtp.timeout", "994"); // 加密端⼝(ssl) 可通过 https:///help/client-profile.html 进⾏查询3334 MailSSLSocketFactory sf = new MailSSLSocketFactory();// SSL加密35 sf.setTrustAllHosts(true); // 设置信任所有的主机36 prop.put("mail.smtp.ssl.enable", "true");37 prop.put("mail.smtp.ssl.socketFactory", sf);3839//设置邮件内容40 JavaMailSenderImpl javaMailSend = new JavaMailSenderImpl();41 MimeMessage message = javaMailSend.createMimeMessage();42 MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "utf-8");43 String nick = MimeUtility.encodeText(from);//设置昵称44 messageHelper.setFrom(new InternetAddress(nick + " <"+username+">"));// 邮件发送者45 messageHelper.setTo(to);46 messageHelper.setSubject(subject);47 messageHelper.setText(text, true);4849//设置邮件服务器登录信息50 javaMailSend.setHost(host);51 javaMailSend.setUsername(username);52 javaMailSend.setPassword(password);53 javaMailSend.setJavaMailProperties(prop);54 ("maillText:" + text);55 javaMailSend.send(message);56 } catch (Exception e) {57// TODO Auto-generated catch block58 log.error(e);59 e.printStackTrace();60 }61 }6263 }注意:1.邮箱密码是开通pop3/smtp服务时所给的授权码,⽽不是你注册邮箱时的真实密码2.检查⾃⼰邮箱是否开通pop3/smtp服务。
通过Java发送邮件
通过Java发送邮件1package com.hrj;23import com.sun.mail.util.MailSSLSocketFactory;45import javax.mail.*;6import javax.mail.internet.InternetAddress;7import javax.mail.internet.MimeMessage;8import .InetAddress;9import java.security.GeneralSecurityException;10import java.util.Properties;1112public class MailDemo01 {13public static void main(String[] args) throws GeneralSecurityException, MessagingException {14// 授权码: ??15 Properties prop = new Properties();16 prop.setProperty("mail.host", "");17 prop.setProperty("mail.transport.protocol", "smtp");18 prop.setProperty("mail.smtp.auth", "true");1920// 关于 QQ 邮箱, 还要设置 SSL 加密, 加上以下代码即可21 MailSSLSocketFactory sf = new MailSSLSocketFactory();22 sf.setTrustAllHosts(true);23 prop.put("mail.smtp.ssl.enable", "true");24 prop.put("mail.smtp.ssl.socketFactory", sf);252627// =================== 使⽤ JavaMail 发送邮件的5个步骤 =================== //28// 1. 创建定义整个应⽤程序所需的环境信息的 Session 对象29 Session session = Session.getDefaultInstance(prop, new Authenticator(){30public PasswordAuthentication getPasswordAuthentication() {31// 发件⼈邮件⽤户名, 密码32return new PasswordAuthentication("2191313025@", "??");33 }34 });3536// 开启 session 的 debug 模式37 session.setDebug(true);3839// 2. 通过 session 获得 transport 对象40 Transport transport = session.getTransport();4142// 3. 使⽤邮箱的⽤户名和授权码连接上邮件服务器43 transport.connect("", "2191313025@", "??");4445// 4. 创建邮件46 MimeMessage message = new MimeMessage(session);47 message.setFrom(new InternetAddress("2191313025@")); // 指明邮件发送⼈48 message.setRecipient(Message.RecipientType.TO, new InternetAddress("2191313025@")); // 指明接收⼈49 message.setSubject("欢迎来到西部开源学习 Java"); // 邮件标题50 message.setContent("滴滴滴, 你好啊!", "text/html;charset=UTF-8");5152// 5. 发送邮件53 transport.sendMessage(message, message.getAllRecipients());5455// 6. 关闭连接56 transport.close();575859 }6061 }。
JAVA中发送电子邮件的方法
JAVA中发送电⼦邮件的⽅法 JAVA中发送邮件的⽅法不复杂,使⽤sun的JavaMail的架包就可以实现,也可以使⽤Spring Boot封装的⽅法,使⽤起来更加便捷。
⼀、下载JavaMail的架包,并导⼊项⽬中,如下:如果是maven项⽬,maven依赖如下:1<dependency>2<groupId>com.sun.mail</groupId>3<artifactId>javax.mail</artifactId>4<version>1.5.6</version>5</dependency>如果使⽤spring的⽅法,还需要导⼊以下maven依赖:1<dependency>2<groupId>org.springframework</groupId>3<artifactId>spring-context-support</artifactId>4<version>4.3.6.RELEASE</version>5</dependency>⼆、使⽤JavaMail发邮件的代码例⼦,如下:1、在main函数中对各项参数进⾏赋值(参数说明已进⾏备注),即可通过send函数进⾏发送邮件操作。
1public class TestEmail {23private final static String TIMEOUT_MS = "20000";45public static void main(String[] args) {6 String host = "";7 String user = "xxxxxx@";8 String password = "xxxxxx";9 String recipients = "xxxxxx@";10 String cc = "";11 String subject = "邮件发送测试";12 String content = "邮件正⽂:<br>你好!";13//⽅式1:通过URL获取附件14// byte[] attachment = FileUtil.getBytesByUrl("http://127.0.0.1/project/test.pdf");15//⽅式2:通过本地路径获取附件16byte[] attachment = FileUtil.getBytesByFile("c://fujian.pdf");1718 String attachmentName = "";19try {20 attachmentName = MimeUtility.encodeWord("这是附件.pdf");21 send(host, user, password, recipients, cc, subject, content, attachment, attachmentName);22 } catch (Exception e) {23 e.printStackTrace();24 }25 }2627/**28 * @param host 邮件服务器主机名29 * @param user ⽤户名30 * @param password 密码31 * @param recipients 收件⼈32 * @param cc 抄送⼈33 * @param subject 主题34 * @param content 内容35 * @param attachment 附件 [没有传 null]36 * @param attachmentName 附件名称 [没有传 null]37 * @throws Exception38*/39public static void send(final String host, final String user, final String password,40final String recipients, final String cc, final String subject, final String content,41final byte[] attachment,final String attachmentName) throws Exception {42 Properties props = new Properties();43 props.put("mail.smtp.host", host);44 props.put("mail.smtp.auth", "true");45 props.put("mail.smtp.timeout", TIMEOUT_MS);4647 Authenticator auth = new Authenticator() {48 @Override49protected PasswordAuthentication getPasswordAuthentication() {50return new PasswordAuthentication(user, password);51 }52 };53 Session session = Session.getInstance(props, auth);54 MimeMessage msg = new MimeMessage(session);55 msg.setFrom(new InternetAddress(user));56 msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));57if (cc != null && cc.length() > 0) {58 msg.setRecipients(, cc);59 }60 msg.setSubject(subject);61// 向multipart对象中添加邮件的各个部分内容,包括⽂本内容和附件62 Multipart multipart = new MimeMultipart();63// 添加邮件正⽂64 BodyPart contentPart = new MimeBodyPart();65 contentPart.setContent(content, "text/html;charset=UTF-8");66 multipart.addBodyPart(contentPart);67// 添加附件的内容68if (attachment!=null) {69 BodyPart attachmentBodyPart = new MimeBodyPart();70 DataSource source = new ByteArrayDataSource(attachment,"application/octet-stream");71 attachmentBodyPart.setDataHandler(new DataHandler(source));72//MimeUtility.encodeWord可以避免⽂件名乱码73 attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachmentName));74 multipart.addBodyPart(attachmentBodyPart);75 }76// 将multipart对象放到message中77 msg.setContent(multipart);78// 保存邮件79 msg.saveChanges();80 Transport.send(msg, msg.getAllRecipients());81 }82 }2、上⾯的例⼦中,如果有附件,可对附件进⾏设置。
javaMail发送邮件(图片,附件)
Java类库中是带有javamail的!所有不需要再下载。
1)运行例子时会出现:Exception in thread "main" ng.NoClassDefFoundError: com/sun/mail/util/LineOutputStream这样的错误,原因是版本不兼容,后来我没有用java ee 5.0而是用j2ee1.4.自己导入mail.jar包就没有出现错误。
2)运行完书本的例子(文本,包含有图片,附件。
另外图片是分为两种,一是引用外部资源,二是嵌入内部)。
对其有个大概的了解。
下面给个完整的例子,包含有图片和附件的。
public class ComplexMessage {/***@param args*@throws MessagingException*@throws AddressException*@throws IOException*@throws FileNotFoundException*/public static void main(String[] args) throws AddressException,MessagingException, FileNotFoundException, IOException{// TODO Auto-generated method stubSession session = Session.getDefaultInstance(new Properties()); // 设置发送邮件的客户端服务器端环境MimeMessage message=createMessage( session);message.writeTo(new FileOutputStream("d:\\test3.eml"));}public static MimeMessage createMessage(Session session) throws AddressException, MessagingException{String from = "4054702459047@";String to = "4074505429047@";String subject = "test";String data = "<FONT face=宋体color=#0909f7 size=7><SPAN style='ACKGROUND-COLOR: #6911ee'><SPAN style='BACKGROUND-COLOR: #000000'><SPAN style='BACKGROUND-COLOR: #000000'><SPAN style='BACKGROUND-COLOR: #ffffff'><EM>华南理工大学</EM> </SPAN></SPAN></SPAN></SPAN></FONT>"+"<img src='cid:test1.jpg'>";Message message = new MimeMessage(session);// 创建MimeMessage实例对象message.setFrom(new InternetAddress(from));message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));message.setSentDate(new Date());message.setSubject(subject);MimeBodyPart contentPart=createContent(data,"d:\\test.jpg");MimeBodyPart attachPart1=createAttachment("d:\\xml.xml");MimeBodyPart attachPart2=createAttachment("d:\\report13.jasper");MimeMultipart multipart=new MimeMultipart("mixed");multipart.addBodyPart(contentPart);multipart.addBodyPart(attachPart1);multipart.addBodyPart(attachPart2);//这里MimeMessage是由MIME对象的消息头和MimeMultipart组成,而MimeMultipart可由//MimeBodyPart 组成。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
*/
private String boundaryNextPart;
/**
*传输邮件所采用的编码
*/
private String contentTransferEncoding;
/**
*设置邮件正文所用的字符集
*/
private String charset;
/**
*内容描述
*/
private String contentDisposition;
contentTypeMap.put("dotm", "application/msword");
}
/**
*该类用来实例化一个正文单元或附件单元对象,他继承了
* {@link Mail}
*,在这里制作这个子类主要是为了区别邮件单元对象和邮件服务对象
*,使程序易读一些。这些邮件单元全部会放到partSet
package com.zlz3907.mail;
import java.io.BufferedReader;
import java.io.File;
import java.io.;
import ja;
import java.io.InputStream;
/**
*值为“true”输出高度信息(包括服务器响应信息),值为“
* false”则不输出调试信息。
*/
private boolean isDebug = true;
/**
*值为“true”则在发送邮件{@link Mail#send()}
*过程中会读取服务器端返回的消息,
*并在邮件发送完毕后将这些消息返回给用户。
/**
*抄送地址
*/
private List<String> cc;
/**
*暗送地址
*/
private List<String> bcc;
/**
*邮件主题
*/
private String subject;
/**
*用户名
*/
private String user;
/**
*密码
*/
private String password;
*/
private List<MailPart> partSet;
/**
*不同类型文件对应的{@link MIME}类型映射。在添加附件
* {@link #addAttachment(String)}
*时,程序会在这个映射中查找对应文件的{@link MIME}
*类型,如果没有,则使用
* {@link #defaultAttachmentContentType}
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
contentTypeMap.put("doc", "application/msword");
contentTypeMap.put("dot", "application/msword");
contentTypeMap.put("docx", "application/msword");
contentTypeMap.put("docm", "application/msword");
*所定义的类型。
*/
private static Map<String, String> contentTypeMap;
static {
// MIME Media Types
contentTypeMap = new HashMap<String, String>();
contentTypeMap.put("xls", "application/vnd.ms-excel");
/**
* MIME邮件类型
*/
private StringcontentType;
/**
*用来绑定多个邮件单元{@link #partSet}
*的分隔标识,我们可以将邮件的正文及每一个附件都看作是一个邮件单元
*。
*/
private String boundary;
/**
*邮件单元分隔标识符,该属性将用来在邮件中作为分割各个邮件单元的标识
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import .Socket;
import java.nio.charset.Charset;
import sun.misc.BASE64Encoder;
/**
*该类使用Socket连接到邮件服务器,
*并实现了向指定邮箱发送邮件及附件的功能。
*
* @author Zhong Lizhi
*/
public class Mail {
/**
*换行符
*/
private static final String LINE_END = "\r\n";
contentTypeMap.put("xlsx", "application/vnd.ms-excel");
contentTypeMap.put("xlsm", "application/vnd.ms-excel");
contentTypeMap.put("xlsb", "application/vnd.ms-excel");
/**
*邮件正文
*/
private String content;
/**
*发送邮件日期的显示格式
*/
private String simpleDatePattern;
/**
*附件的默认MIME类型
*/
private String defaultAttachmentContentType;
/**
*邮件单元的集合,用来存放正文单元和所有的附件单元。
*/
private boolean isAllowReadSocketInfo = true;
/**
*邮件服务器地址
*/
private String host;
/**
*发件人邮箱地址
*/
private String from;
/**
*收件人邮箱地址
*/
private List<String> to;