java发送邮件及邮 件附件代码实例

合集下载

Java实现发送邮件并携带附件

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实现简单发送邮件功能

java实现简单发送邮件功能

java实现简单发送邮件功能本⽂实例为⼤家分享了java实现简单发送邮件的具体代码,供⼤家参考,具体内容如下添加依赖<!--发送邮件API--><!-- https:///artifact/javax.mail/javax.mail-api --><dependency><groupId>javax.mail</groupId><artifactId>javax.mail-api</artifactId><version>1.6.2</version></dependency><!-- https:///artifact/com.sun.mail/javax.mail --><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.2</version></dependency>⾃定义异常类public class EmailException extends Exception {public EmailException(String message) {super(message);}public EmailException() {super();}/****/private static final long serialVersionUID = 115631651651651651L;}IMAP协议读取邮件import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Properties;import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.Flags;import javax.mail.Folder;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.Part;import javax.mail.Session;import javax.mail.Store;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.internet.MimeUtility;import com.sun.mail.util.MailSSLSocketFactory;public class IMAPReceiveMail {private String user = "";//账号private String password = "";//密码private String HOST = ""; // smtp服务器// private Properties props = null;private Folder folder = null;//收件箱private Store store = null;//实例对象// final String pop3 = "IMAP";final String imap = "imap";public IMAPReceiveMail(String user,String password) {this.password = password;//密码er = user;//账户}/*** @param message 邮件对象* @param to 收件⼈* @throws MessagingException* @throws IOException*/// public void forwardMail(Message message,String to) throws MessagingException, IOException {// Message forward = new MimeMessage(session);// forward.setSubject(message.getSubject());// forward.setFrom(new InternetAddress(to));// forward.setRecipient(Message.RecipientType.TO, new InternetAddress(to));// forward.setSentDate(new Date());// forward.setContent(message.getContent(), message.getContentType());//// Transport smtp = session.getTransport("smtp");// smtp.connect(HOST, user, password);//连接服务器的邮箱// smtp.sendMessage(forward, forward.getAllRecipients());// smtp.close();// }/*** 接收邮件*/public Folder resceive() throws Exception {/*** 因为现在使⽤的是163邮箱⽽163的 pop地址是 端⼝是 110 ⽐如使⽤好未来企业邮箱就需要换成好未来邮箱的* pop服务器地址 和端⼝ 110*/String duankou = ""; // 端⼝号String servicePath = ""; // 服务器地址if(user==null||user.length()==0) throw new EmailException("账户不能为空");if(password==null||password.length()==0) throw new EmailException("密码不能为空");if(user.contains("@163")) {duankou = "143"; // 端⼝号servicePath = ""; // 服务器地址}else if(user.contains("@qq")) {duankou = "993"; // 端⼝号servicePath = ""; // 服务器地址}else {throw new EmailException("不⽀持该协议");}// 准备连接服务器的会话信息Properties props = new Properties();props.setProperty("mail.store.protocol", imap); // 使⽤pop3协议props.setProperty("mail.imap.socketFactory.fallback", "false");props.setProperty("mail.imap.port", duankou); // 端⼝props.setProperty("mail.imap.socketFactory.port", duankou); // 端⼝props.setProperty("mail.transport.protocol", "smtp");// 发送邮件协议名称props.setProperty("mail.smtp.auth", "true"); //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(⼀定要有这⼀条props.setProperty("mail.host", HOST);//关闭读取附件时分批获取 BASE64 输⼊流的配置props.setProperty("mail.imap.partialfetch", "false");props.setProperty("mail.imaps.partialfetch", "false");// props.setProperty("mail.pop3.host", servicePath); // pop3服务器// final String SSL_FACTORY = ".ssl.SSLSocketFactory";// Security.addProvider(new .ssl.internal.ssl.Provider());// props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);MailSSLSocketFactory sf = new MailSSLSocketFactory();//ssl加密sf.setTrustAllHosts(true);props.put("mail.imap.ssl.enable", "true");props.put("mail.imap.ssl.socketFactory", sf);// 创建Session实例对象Session session = Session.getInstance(props);session.setDebug(false);store = session.getStore(imap);store.connect(servicePath,user,password); // 163邮箱程序登录属于第三⽅登录所以这⾥的密码是163给的授权密码⽽并⾮普通的登录密码 // 获得收件箱folder = store.getFolder("INBOX");/** Folder.READ_ONLY:只读权限 Folder.READ_WRITE:可读可写(可以修改邮件的状态)*/folder.open(Folder.READ_WRITE); // 打开收件箱// 由于POP3协议⽆法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数// System.out.println("未读邮件数: " + folder.getUnreadMessageCount());// 由于POP3协议⽆法获知邮件的状态,所以下⾯得到的结果始终都是为0// System.out.println("删除邮件数: " + folder.getDeletedMessageCount());// System.out.println("新邮件: " + folder.getNewMessageCount());// 获得收件箱中的邮件总数// System.out.println("邮件总数: " + folder.getMessageCount());// 得到收件箱中的所有邮件,并解析// Message[] messages = folder.getMessages();// parseMessage(messages);// 得到收件箱中的所有邮件并且删除邮件// deleteMessage(messages);// 释放资源// folder.close(true);// store.close();return folder;}public void Colsefolder() throws MessagingException {//关闭资源if(folder!=null) {folder.close();}if(store!=null) {store.close();}}/*** 解析邮件** @param messages 要解析的邮件列表*/public void parseMessage(Message... messages) throws MessagingException, IOException {if (messages == null || messages.length < 1)throw new MessagingException("未找到要解析的邮件!");// 解析所有邮件for (int i = 0, count = messages.length; i < count; i++) {MimeMessage msg = (MimeMessage) messages[i];System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");System.out.println("主题: " + getSubject(msg));System.out.println("发件⼈: " + getFrom(msg));System.out.println("收件⼈:" + getReceiveAddress(msg, null));System.out.println("发送时间:" + getSentDate(msg, null));System.out.println("是否已读:" + isSeen(msg));System.out.println("邮件优先级:" + getPriority(msg));System.out.println("是否需要回执:" + isReplySign(msg));System.out.println("邮件⼤⼩:" + msg.getSize() * 1024 + "kb");boolean isContainerAttachment = isContainAttachment(msg);System.out.println("是否包含附件:" + isContainerAttachment);if (isContainerAttachment) {saveAttachment(msg, "f:\\mailTest\\" + msg.getSubject() + "_" + i + "_"); // 保存附件}StringBuffer content = new StringBuffer(30);getMailTextContent(msg, content);System.out.println("邮件正⽂:" + (content.length() > 100 ? content.substring(0, 100) + "..." : content));System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");System.out.println();}}/*** 解析邮件** @param messages 要解析的邮件列表*/public void deleteMessage(Message... messages) throws MessagingException, IOException {if (messages == null || messages.length < 1)throw new MessagingException("未找到要解析的邮件!");// 解析所有邮件for (int i = 0, count = messages.length; i < count; i++) {/*** 邮件删除*/Message message = messages[i];String subject = message.getSubject();// set the DELETE flag to truemessage.setFlag(Flags.Flag.DELETED, true);System.out.println("Marked DELETE for message: " + subject);}}/*** 获得邮件主题** @param msg 邮件内容* @return 解码后的邮件主题*/public String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {return MimeUtility.decodeText(msg.getSubject());}/*** 获得邮件发件⼈** @param msg 邮件内容* @return 姓名 <Email地址>* @throws MessagingException* @throws UnsupportedEncodingException*/public String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {String from = "";Address[] froms = msg.getFrom();if (froms.length < 1)throw new MessagingException("没有发件⼈!");InternetAddress address = (InternetAddress) froms[0];String person = address.getPersonal();if (person != null) {person = MimeUtility.decodeText(person) + " ";} else {person = "";}from = person + "<" + address.getAddress() + ">";return from;}public String getFromAddress(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {String from = "";Address[] froms = msg.getFrom();if (froms.length < 1)throw new MessagingException("没有发件⼈!");InternetAddress address = (InternetAddress) froms[0];from = address.getAddress();return from;}/*** 根据收件⼈类型,获取邮件收件⼈、抄送和密送地址。

个人java邮件发送程序例子

个人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实现发送邮件,图片,附件

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 发送邮件

使用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的例子。

javamail收发邮件(带附件,正文带图)

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 对象。

161013、java实现邮件群发带附件

161013、java实现邮件群发带附件

161013、java实现邮件群发带附件要完成Java群发邮件功能,⾸先须加⼊mail.jar和activation.jar这两个包下⾯是邮件的例⼦:import java.io.File;import java.util.Properties;import java.util.Vector;import javax.mail.internet.MimeUtility;/*** 发送邮件的信息类* @author 仇志鹏* @version 2016.10.19**/public class MailSenderInfo {// 发送邮件的服务器的IP和端⼝private String mailServerHost;private String mailServerPort = “25”;// 邮件发送者的地址private String fromAddress;// 邮件接收者的地址private String[] toAddress;// 登陆邮件发送服务器的⽤户名和密码private String userName;private String password;// 是否需要⾝份验证private boolean validate = false;// 邮件主题private String subject;// 邮件的⽂本内容private String content;// 邮件附件的⽂件名private String fileName = “” ;//附件⽂件集合private Vector file = new Vector() ;/*** 获得邮件会话属性* @return*/public Properties getProperties(){Properties p = new Properties();p.put(“mail.smtp.host”, this.mailServerHost);p.put(“mail.smtp.port”, this.mailServerPort);p.put(“mail.smtp.auth”, validate ? “true” : “false”);return p;}public String getMailServerHost() {return mailServerHost;}public void setMailServerHost(String mailServerHost) {this.mailServerHost = mailServerHost;}public String getMailServerPort() {return mailServerPort;}public void setMailServerPort(String mailServerPort) {this.mailServerPort = mailServerPort;}public boolean isValidate() {return validate;}public void setValidate(boolean validate) {this.validate = validate;}public String getFromAddress() {return fromAddress;}public void setFromAddress(String fromAddress) {this.fromAddress = fromAddress;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String[] getToAddress() {return toAddress;}public void setToAddress(String[] toAddress) {this.toAddress = toAddress;}public String getUserName() {return userName;}public void setUserName(String userName) {erName = userName;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getContent() {return content;}public void setContent(String textContent) {this.content = textContent;}public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}public Vector getFile() {return file;}public void setFile(Vector file) {this.file = file;}/**** ⽅法说明:把主题转换为中⽂* 输⼊参数:String strText* 返回类型:*/public String transferChinese(String strText) {try {strText = MimeUtility.encodeText(new String(strText.getBytes(),“GB2312”), “GB2312”, “B”);} catch (Exception e) {e.printStackTrace();}return strText;}}———————————————————import javax.mail.Authenticator;import javax.mail.PasswordAuthentication;/*** 发邮件的⾝份验证器* @author 仇志鹏* @version 2016.10.19**/public class MyAuthenticator extends Authenticator{String userName=null;String password=null;public MyAuthenticator(){}public MyAuthenticator(String username, String password) { erName = username;this.password = password;}protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(userName, password);}}———————————————————————import java.io.File;import java.util.Date;import java.util.Enumeration;import java.util.Properties;import java.util.Vector;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Address;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;public class SimpleMailSender {/** *//*** 以⽂本格式发送邮件* @param mailInfo 待发送的邮件的信息*/public boolean sendTextMail(MailSenderInfo mailInfo) {// 判断是否需要⾝份认证MyAuthenticator authenticator = null;Properties pro = mailInfo.getProperties();if (mailInfo.isValidate()) {// 如果需要⾝份认证,则创建⼀个密码验证器authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); }// 根据邮件会话属性和密码验证器构造⼀个发送邮件的sessionSession sendMailSession = Session.getDefaultInstance(pro,authenticator);try {// 根据session创建⼀个邮件消息Message mailMessage = new MimeMessage(sendMailSession);// 创建邮件发送者地址 authenticatorAddress from = new InternetAddress(mailInfo.getFromAddress());// 设置邮件消息的发送者mailMessage.setFrom(from);// 创建邮件的接收者地址,并设置到邮件消息中String[] mailToAddress = mailInfo.getToAddress() ;int len = mailToAddress.length ;Address to[] = new InternetAddress[len] ;for(int i=0;i<len;i++){to[i] = new InternetAddress(mailToAddress[i]) ;}// Message.RecipientType.TO属性表⽰接收者的类型为TO//TO表⽰主要接收⼈,CC表⽰抄送⼈,BCC表⽰秘密抄送⼈。

java邮件发送(单人,多人,抄送,Excel附件)

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;}}。

javaemail发送邮件(带附件)

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发送邮件(带附件)

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利用springJavaMailSenderImpl发送邮件,支持普通文本、附件、。。。

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) 等,可暂时不考虑。

javamail发送文本邮件、HTML邮件及带附件邮件

javamail发送文本邮件、HTML邮件及带附件邮件

javamail发送文本邮件、HTML邮件及带附件邮件MailInfo.java[java] view plain copyimportjava.util.Properties; public class MailInfo{ private String mailServerHost;// 服务器ipprivate String mailServerPort;// 端口private String fromAddress;// 发送者的邮件地址private String toAddress;// 邮件接收者地址private String username;// 登录邮件发送服务器的用户名private String password;// 登录邮件发送服务器的密码private boolean validate = false;// 是否需要身份验证private String subject;// 邮件主题private String content;// 邮件内容private String[] attachFileNames;// 附件名称public Properties getProperties() { Properties p = new Properties(); p.put("mail.smtp.host",this.mailServerHost); p.put("mail.smtp.port", this.mailServerPort); p.put("mail.smtp.auth", validate ? "true" : "false"); return p; } public String getMailServerHost() { return mailServerHost; } public void setMailServerHost(String mailServerHost){ this.mailServerHost = mailServerHost; } public String getMailServerPort() { return mailServerPort; } public void setMailServerPort(String mailServerPort){ this.mailServerPort = mailServerPort; } public String getFromAddress() { return fromAddress; } public void setFromAddress(String fromAddress){ this.fromAddress = fromAddress; } public String getToAddress() { return toAddress; } public voidsetToAddress(String toAddress){ this.toAddress = toAddress; }public String getUsername() { return username; } public void setUsername(String username) { ername = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isValidate() { returnvalidate; } public void setValidate(boolean validate) { this.validate = validate; }public String getSubject() { returnsubject; } public void setSubject(String subject) { this.subject = subject; }public String getContent() { returncontent; } public void setContent(String content) { this.content = content; }public String[] getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(String[] attachFileNames){ this.attachFileNames =attachFileNames; } }MyAuthenticator.Java[java] view plain copyimportjavax.mail.Authenticator; importjavax.mail.PasswordAuthentication; public class MyAuthenticator extends Authenticator { private String username = null; private String password = null; public MyAuthenticator() { };public MyAuthenticator(String username, String password) { ername = username;this.password = password; } protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(username,password); } } SimpleMail.java[java] view plain copyimport java.io.File; import java.util.Date; import java.util.Properties; importjavax.activation.DataHandler; importjavax.activation.FileDataSource; importjavax.mail.Address; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; importjavax.mail.internet.InternetAddress; importjavax.mail.internet.MimeBodyPart; importjavax.mail.internet.MimeMessage; importjavax.mail.internet.MimeMultipart; public class SimpleMail { // 以文本格式发送邮件public static boolean sendTextMail(MailInfo mailInfo){ //判断是否需要身份认证MyAuthenticator authenticator = null; Properties properties = mailInfo.getProperties(); if (mailInfo.isValidate()) { //如果需要身份认证,则创建一个密码验证器authenticator = new MyAuthenticator(mailInfo.getUsername(),mailInfo.getPassword()); }//根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(properties, authenticator);try { Message mailMessage = new MimeMessage(sendMailSession);//根据session创建一个邮件消息Address from = new InternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址mailMessage.setFrom(from);//设置邮件消息的发送者Address to = new InternetAddress(mailInfo.getToAddress());//创建邮件的接收者地址mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的接收者mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题mailMessage.setSentDate(new Date());//设置邮件消息发送的时间//mailMessage.setText(mailInfo.getContent());//设置邮件消息的主要内容//MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象Multipart mainPart = new MimeMultipart(); MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含附件内容的MimeBodyPart //设置HTML内容messageBodyPart.setContent(mailInfo.getContent(),"text/ html; charset=utf-8");mainPart.addBodyPart(messageBodyPart);//存在附件String[] filePaths =mailInfo.getAttachFileNames(); if (filePaths != null &amp;&amp; filePaths.length &gt; 0) { for(StringfilePath:filePaths){ messageBody Part = new MimeBodyPart(); File file = new File(filePath);if(file.exists()){//附件存在磁盘中FileDataSource fds = new FileDataSource(file);//得到数据源messageBodyPart.setDataHandler(newDataHandler(fds));//得到附件本身并至入BodyPart messageBodyPart.setFileName(file.getName());//得到文件名同样至入BodyPartmainPart.addBodyPart(messageBodyPart);} } }//将MimeMultipart对象设置为邮件内容mailMessage.setContent(mainPart);Transport.send(mailMessage);//发送邮件return true; } catch (Exception e){ e.printStackTrace(); }return false; } // 以HTML格式发送邮件public static boolean sendHtmlMail(MailInfo mailInfo) { //判断是否需要身份认证MyAuthenticator authenticator = null; Properties properties = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器authenticator = new MyAuthenticator(mailInfo.getUsername(),mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession =Session.getDefaultInstance(properties, authenticator);try{ Message mailMessage = new MimeMessage(sendMailSession);//根据session创建一个邮件消息Address from = new InternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址mailMessage.setFrom(from);//设置邮件消息的发送者Address to = new InternetAddress(mailInfo.getToAddress());//创建邮件的接收者地址mailMessage.setRecipient(Message.RecipientType.TO, to);//设置邮件消息的接收者mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题mailMessage.setSentDate(new Date());//设置邮件消息发送的时间//MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象Multipart mainPart = new MimeMultipart(); MimeBodyPart messageBodyPart = new MimeBodyPart();//创建一个包含HTML内容的MimeBodyPart //设置HTML 内容messageBodyPart.setContent(mailInfo.getContent(),"text/ html; charset=utf-8");mainPart.addBodyPart(messageBodyPart);//存在附件String[] filePaths =mailInfo.getAttachFileNames(); if (filePaths != null &amp;&amp; filePaths.length &gt; 0){ for(StringfilePath:filePaths){ messageBody Part = new MimeBodyPart(); File file = new File(filePath);if(file.exists()){//附件存在磁盘中FileDataSource fds = new FileDataSource(file);//得到数据源messageBodyPart.setDataHandler(newDataHandler(fds));//得到附件本身并至入BodyPart messageBodyPart.setFileName(file.getName());//得到文件名同样至入BodyPartmainPart.addBodyPart(messageBodyPart);} } }//将MimeMultipart对象设置为邮件内容mailMessage.setContent(mainPart);Transport.send(mailMessage);//发送邮件return true; }catch (Exception e){ e.printStackTrace(); }return false; } } emailTest.java[java] view plain copypublic class emailTest { public static voidmain(String[] args) { MailInfo mailInfo = new MailInfo();mailInfo.setMailServerHost("");mailInfo.setMailServerPort("25");mailInfo.setValidate(true);mailInfo.setUsername("xxx@");mailInfo.setPassword("xxxxx");// 您的邮箱密码mailInfo.setFromAddress("xxxx@");mailInfo.setToAddress("xxxx@");mailInfo.setSubject("设置邮箱标题");//附件String[]attachFileNames={"d:/Sunset.jpg"};mailInfo.setAttachFileNames(attachFileNames);// 这个类主要来发送邮件//mailInfo.setContent("设置邮箱内容");//SimpleMail.sendTextMail(mailInfo);// 发送文体格式StringBuffer demo = new StringBuffer();demo.append("&lt;!DOCTYPE html PUBLIC\"-//W3C//DTD HTML 4.01 Transitional//EN\"\"/TR/html4/loose.dtd\"&gt;") . append("&lt;html&gt;") .append("&lt;head&gt;") .append("&lt;meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"&gt;") .append("&lt;title&gt;测试邮件&lt;/title&gt;") .append("&lt;styletype=\"text/css\"&gt;") .append(".test{font-family :\"Microsoft Yahei\";font-size: 18px;color:red;}") .append("&lt;/style&gt;") .append("&lt;/head&gt;") .append("&lt;body&gt;") .append("&lt;span class=\"test\"&gt;大家好,这里是测试Demo&lt;/span&gt;") .append("&lt;/body&gt;") .append("&lt;/html&gt;");mailInfo.setContent(demo.toString());SimpleMail.sendHtmlMail(mailInfo);// 发送html格式} }。

JAVA发送邮件

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发邮件

Java发邮件的例子,JavaMail实例代码,邮件发送在Java中不是难点,但很实用,很多程序都是基于网络的,所以邮件的发送已经成为基础功能了。

核心主文件代码如下:001package com.pb.mail;002import java.util.Properties;003import javax.mail.Address;004import javax.mail.BodyPart;005import javax.mail.Message;006import javax.mail.Multipart;007import javax.mail.Session;008import javax.mail.Transport;009import javax.mail.internet.InternetAddress;010import javax.mail.internet.MimeBodyPart;011import javax.mail.internet.MimeMessage;012import javax.mail.internet.MimeMultipart;013public class Mail{014private MimeMessage mimeMsg;015private Session session;016private Properties props;017private String username;018private String password;019private Multipart mp;020public Mail(String smtp){021setSmtpHost(smtp);022createMimeMessage();023}024public void setSmtpHost(String hostName){025System.out.println("设置系统属性:mail.smtp.host="+hostName); 026if(props==null){027props=System.getProperties();028}029props.put("mail.smtp.host",hostName);030}031public boolean createMimeMessage(){032try{033System.out.println("准备获取邮件会话对象!");034session=Session.getDefaultInstance(props,null);035}catch(Exception e){036System.out.println("获取邮件会话错误!"+e);037return false;038}039System.out.println("准备创建MIME邮件对象!");041mimeMsg=new MimeMessage(session);042mp=new MimeMultipart();043044return true;045}catch(Exception e){046System.out.println("创建MIME邮件对象失败!"+e);047return false;048}049}050051/*定义SMTP是否需要验证*/052public void setNeedAuth(boolean need){053System.out.println("设置smtp身份认证:mail.smtp.auth="+need); 054if(props==null)055props=System.getProperties();056if(need){057props.put("mail.smtp.auth","true");058}else{059props.put("mail.smtp.auth","false");060}061}062public void setNamePass(String name,String pass){063username=name;064password=pass;065}066067/*定义邮件主题*/068public boolean setSubject(String mailSubject){069System.out.println("定义邮件主题!");070try{071mimeMsg.setSubject(mailSubject);072return true;073}catch(Exception e){074System.err.println("定义邮件主题发生错误!");075return false;076}077}078079/*定义邮件正文*/080public boolean setBody(String mailBody){081try{082BodyPart bp=new MimeBodyPart();083bp.setContent(""+mailBody,"text/html;charset=GBK");085return true;086}catch(Exception e){087System.err.println("定义邮件正文时发生错误!"+e); 088return false;089}090}091092/*设置发信人*/093public boolean setFrom(String from){094System.out.println("设置发信人!");095try{096mimeMsg.setFrom(new InternetAddress(from));//发信人097return true;098}catch(Exception e){099return false;100}101}102103/*定义收信人*/104public boolean setTo(String to){105if(to==null)106return false;107System.out.println("定义收信人!");108try{109mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));110return true;111}catch(Exception e){112return false;113}114}115116/*定义抄送人*/117public boolean setCopyTo(String copyto){118if(copyto==null)119return false;120try{121mimeMsg.setRecipients(, (Address[])InternetAddress122.parse(copyto));123return true;124}catch(Exception e){125return false;127}128129/*发送邮件模块*/130public boolean sendOut(){131try{132mimeMsg.setContent(mp);133mimeMsg.saveChanges();134System.out.println("邮件发送中....");135Session mailSession=Session.getInstance(props,null); 136Transport transport=mailSession.getTransport("smtp"); 137transport.connect((String)props.get("mail.smtp.host"), username,password);138transport.sendMessage(mimeMsg,mimeMsg139.getRecipients(Message.RecipientType.TO));140System.out.println("发送成功!");141transport.close();142return true;143}catch(Exception e){144System.err.println("邮件失败!"+e);145return false;146}147}148149/*调用sendOut方法完成发送*/150public static boolean sendAndCc(String smtp,String from,String to, String copyto,151String subject,String content,String username,String password) {152Mail theMail=new Mail(smtp);153theMail.setNeedAuth(true);//验证154if(!theMail.setSubject(subject))155return false;156if(!theMail.setBody(content))157return false;158if(!theMail.setTo(to))159return false;160if(!theMail.setCopyTo(copyto))161return false;162if(!theMail.setFrom(from))163return false;164theMail.setNamePass(username,password);165if(!theMail.sendOut())166return false;167return true;168}169}以下文件代码也必需的:01package com.pb.mail;02public class SendMail{03public static void main(String[]args){04String smtp="";//smtp服务器05String from="abcdefg@";//邮件显示名称06String to="123456@";//收件人的邮件地址,必须是真实地址07String copyto="";//抄送人邮件地址08String subject="测试邮件";//邮件标题09String content="你好!";//邮件内容10String username="abcdefg";//发件人真实的账户名11String password="123456789";//发件人密码12Mail.sendAndCc(smtp,from,to,copyto,subject,content, username,password);13}14}文件名自拟,搞Java的都知道自己弄,不多费话了,亲测可用,你如果真用不了,那我真没办法!~~。

Java实现网易企业邮箱发送邮件

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中发送电子邮件的方法

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发送邮件(图片,附件)

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. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
for (int i = partCount - 1; i >= 0; i--) {
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");
contentTypeMap.put("docm", "application/msword");
*/
private List<MailPart> partSet;
/**
*不同类型文件对应的{@link MIME}类型映射。在添加附件
* {@link #addAttachment(String)}
*时,程序会在这个映射中查找对应文件的{@link MIME}
*类型,如果没有,则使用
* {@link #defaultAttachmentContentType}
* @param charset
*原字符串的编码格式
* @return base64编码格式的字符
*/
private String toBase64(String str, String charset) {
if (null != str) {
try {
return toBase64(str.getBytes(charset));
import java.util.Map;
import sun.misc.BASE64Encoder;
/**
*该类使用Socket连接到邮件服务器,
*并实现了向指定邮箱发送邮件及附件的功能。
*
* @author Zhong Lizhi
*/
public class Mail {
/**
*换行符
*/
private static final String LINE_END = "\r\n";
}
}
/**
*默认构造函数
*/
public Mail() {
defaultAttachmentContentType = "application/octet-stream";
simpleDatePattern = "yyyy-MM-dd HH:mm:ss";
boundary = "--=_NextPart_zlz_3907_" + System.currentTimeMillis();
*所定义的类型。
*/
private static Map<String, String> contentTypeMap;
static {
// MIME Media Types
contentTypeMap = new HashMap<String, String>();
contentTypeMap.put("xls", "application/vnd.ms-excel");
sbd.append(getBoundaryNextPart()).append(LINE_END);
sbd.append("Content-Type: ");
sbd.append(attachment.getContentType());
sbd.append(LINE_END);
sbd.append("Content-Transfer-Encoding: ");
}
/**
*将所有的邮件单元按照标准的MIME格式要求合并。
*
* @return返回一个所有单元合并后的字符串。
*/
private String getAllParts() {
int partCount = partSet.size();
StringBuilder sbd = new StringBuilder(LINE_END);
partSet = new ArrayList<MailPart>();
to = new ArrayList<String>();
cc = new ArrayList<String>();
bcc = new ArrayList<String>();
}
/**
*根据指定的完整文件名在
* {@link #contentTypeMap}
/**
* MIME邮件类型
*/
private String contentType;
/**
*用来绑定多个邮件单元{@link #partSet}
*的分隔标识,我们可以将邮件的正文及每一个附件都看作是一个邮件单元
*。
*/
private String boundary;
/**
*邮件单元分隔标识符,该属性将用来在邮件中作为分割各个邮件单元的标识
/**
*邮件正文
*/
private String content;Leabharlann /***发送邮件日期的显示格式
*/
private String simpleDatePattern;
/**
*附件的默认MIME类型
*/
private String defaultAttachmentContentType;
/**
*邮件单元的集合,用来存放正文单元和所有的附件单元。
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
String ret = null;
if (null != fileName) {
int flag = stIndexOf(".");
if (0 <= flag && flag < fileName.length() - 1) {
fileName = fileName.substring(flag + 1);
sbd.append(LINE_END);
/**
*抄送地址
*/
private List<String> cc;
/**
*暗送地址
*/
private List<String> bcc;
/**
*邮件主题
*/
private String subject;
/**
*用户名
*/
private String user;
/**
*密码
*/
private String password;
sbd.append(attachment.getContentTransferEncoding());
sbd.append(LINE_END);
if (i != partCount - 1) {
sbd.append("Content-Disposition: ");
sbd.append(attachment.getContentDisposition());
*中,在发送邮件{@link #send()}时,程序会调用
* {@link #getAllParts()}
*方法将所有的单元合并成一个符合MIME格式的字符串。
*
* @author Zhong Lizhi
*/
private class MailPart extends Mail {
public MailPart() {
return new BASE64Encoder().encode(bs);
}
/**
*将给定字符串转换为base64编码的字符串
*
* @param str
*需要转码的字符串
* @return base64编码格式的字符
相关文档
最新文档