JAVAMAIL发送邮件实例 给多人发送、抄送

合集下载

Java发送邮件——SpringBoot集成JavaMail

Java发送邮件——SpringBoot集成JavaMail

Java发送邮件——SpringBoot集成JavaMail ⽤途:此⽂仅供,⾃⼰今后的⼩程序通过邮件,批量通知⽤户。

简单记录了⼀些发送基本邮件的操作。

项⽬(SpringBoot版本为2.1.2.RELEASE):核⼼依赖(其他相关依赖,在其使⽤的地⽅具体说明):<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>application.yml——邮件发送相关配置:spring:mail:host: username: ***@password: *** #qq邮箱开启POP3/SMTP服务后,⽣成的授权码receiver: ***@protocol: smtpdefault-encoding: utf-8邮件实体类(使⽤Lombok的注解简化实体构造):import lombok.Data;import org.springframework.core.io.FileSystemResource;@Datapublic class MailBean {private String subject;private String text;private FileSystemResource file;private String attachmentFilename;private String contentId;}简单封装邮件发送的⼯具类:import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import ponent;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;@Componentpublic class MailUtil {private final JavaMailSender mailSender;@Value("${ername}")private String sender;@Value("${spring.mail.receiver}")private String receiver;@Autowiredpublic MailUtil(JavaMailSender mailSender) {this.mailSender = mailSender;}public void sendMailSimple() {SimpleMailMessage mimeMessage = new SimpleMailMessage();mimeMessage.setFrom(sender);mimeMessage.setTo(receiver);mimeMessage.setSubject("主题");mimeMessage.setText("正⽂");mailSender.send(mimeMessage);}private void sendMail(MailBean mailBean, boolean html, boolean multipart) {MimeMessage mimeMessage = mailSender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart); helper.setFrom(sender);helper.setTo(receiver);helper.setSubject(mailBean.getSubject());helper.setText(mailBean.getText(), html);if (mailBean.getFile() != null) {helper.addAttachment(mailBean.getAttachmentFilename(), mailBean.getFile()); }} catch (MessagingException e) {e.printStackTrace();}mailSender.send(mimeMessage);}public void sendMail(MailBean mailBean) {sendMail(mailBean, true, true);}public void sendMailText(MailBean mailBean) {sendMail(mailBean, false, false);}public void sendMailHtml(MailBean mailBean) {sendMail(mailBean, true, false);}public void sendMailInline(MailBean mailBean) {MimeMessage mimeMessage = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);try {helper.setFrom(sender);helper.setTo(receiver);helper.setSubject(mailBean.getSubject());helper.setText(mailBean.getText(), true);helper.addInline(mailBean.getContentId(), mailBean.getFile());} catch (MessagingException e) {e.printStackTrace();}mailSender.send(mimeMessage);}}单元测试就不写了,忘记怎么写了。

发送邮件—java代码简单实例

发送邮件—java代码简单实例

发送邮件—java代码简单实例java某.mail1.准备jar包修改环境变量编辑CLASSPATH,在其后添加:%JAVA_HOME%\lib\mail.jar JAVA_HOME是jdk根目录,这里不做解释。

2.源代码//SendMail.javaimportjava.util.Propertie;importjava某.activation.DataHandler;importjava某.activation.FileDataSource;importjava某.mail.Addre;importjava某.mail.BodyPart;importjava某.mail.Meage;importjava某.mail.Multipart;importjava某.mail.Seion;java某.mailimportjava某.mail.Tranport;importjava某.mail.internet.InternetAddre;importjava某.mail.internet.MimeBodyPart;importjava某.mail.internet.MimeMeage;importjava某.mail.internet.MimeMultipart;importjava某.mail.Authenticator;importjava某.mail.PawordAuthentication;publicclaSendMail{}claMail{privateMimeMeagemimeMg;//MIME邮件对象privateSeioneion;//邮件会话对象privatePropertieprop;//系统属性privatebooleanneedAuth=fale;//mtp是否需要认证//mtp认证用户名和密码privateStringuername;privateStringpaword;privateMultipartmp;//Mu ltipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMeage对象java某.mailjava某.mailjava某.mailjava某.mailtry{mimeMg.etRecipient(,(Addre[])InternetAddre.pare(copyto));returntrue;}catch(E某ceptione){returnfale;}}/某某某发送邮件某/publicbooleanendOut(){try{mimeMg.etContent(mp);mimeMg.aveChange ();Sytem.out.println("正在发送邮件....");SeionmailSeion=Seion.getIntance(prop,null);//Sytem.out. println("111111");Tranporttranport=mailSeion.getTranport("mtp");java某.mailtranport.connect((String)prop.get("mail.mtp.hot"),uername,pa word);//Sytem.out.println("333333");tranport.endMeage(mimeMg,mim eMg.getRecipient(Meage.RecipientType.TO));//Sytem.out.println("4 44444");tranport.endMeage(mimeMg,mimeMg.getRecipient());//tranpo rt.end(mimeMg);Sytem.out.println("发送邮件成功!");tranport.cloe();returntrue;}catch(E某ceptione){Sytem.err.println("邮件发送失败!"+e);returnfale;}}/某某某调用endOut方法完成邮件发送某/publictaticbooleanend(Stringmtp,String content,Stringuername,Stringpaword){ MailtheMail=newMail(mtp);theMail.etNeedAuth(true);//需要验证if(!theMail.etSubject(ubject))returnfale; if(!theMail.etBody(content))returnfale; if(!theMail.etTo(to))returnfale;if(!theMail.etFrom(from))returnfale; theMail.etNamePa(uername,paword);if(!theMail.endOut())returnfale; returntrue;}from,Stringto,Stringubject,Stringjava某.mailpublictaticbooleanendAndCc(Stringmtp,Stringfrom,Stringto,Str ingcopyto,Stringubject,Stringcontent,Stringuername,Stringpaword) {MailtheMail=newMail(mtp);theMail.etNeedAuth(true);//需要验证java某.mailpublictaticbooleanendAndCc(Stringmtp,Stringfrom,Stringto,Str ingcopyto,Stringubject,Stringcontent,Stringuername,Stringpaword, Stringfilename){}MailtheMail=newMail(mtp);theMail.etNeedAuth(true);//需要验证if(!theMail.etSubject(ubject))returnfale;if(!theMail.etBody(cont ent))returnfale;if(!theMail.addFileAffi某(filename))returnfale;if(!theMail.etTo(to))returnfale;if(!theMai l.etCopyTo(copyto))returnfale;if(!theMail.etFrom(from))returnfal e;theMail.etNamePa(uername,paword);if(!theMail.endOut())returnfa le;returntrue;}。

java mail 抄送

java mail 抄送

java mail 抄送标题:Java Mail 抄送的重要性及使用方法在日常的工作和生活中,我们经常需要通过电子邮件进行沟通和交流。

而在发送邮件时,抄送功能是非常常见且重要的一个选项。

本文将介绍Java Mail抄送的重要性及使用方法,让我们更加高效地进行邮件通信。

一、为什么需要使用Java Mail抄送功能?在实际的工作场景中,我们常常需要将邮件抄送给多个人,以便让更多的人了解和参与到邮件的讨论和决策中来。

通过使用Java Mail 抄送功能,可以简单方便地将邮件同时发送给多个收件人,节省了我们的时间和精力。

二、使用Java Mail进行抄送的方法1. 创建Java Mail的Session对象在使用Java Mail进行邮件发送时,首先需要创建一个Session对象。

Session对象代表了和邮件服务器的会话,我们可以通过它来建立与邮件服务器的连接。

2. 创建Java Mail的Message对象在创建Message对象时,我们可以设置邮件的标题、正文、发件人等信息。

同时,我们还可以通过Message的setRecipients方法来设置收件人、抄送人和密送人。

3. 设置抄送人通过使用Message的addRecipient方法,并指定RecipientType为CC,我们可以将邮件抄送给指定的收件人。

4. 设置邮件内容在设置邮件的内容时,我们可以使用Java Mail提供的丰富的API来自定义邮件的格式和样式。

可以设置邮件的文本内容、HTML内容、附件等。

5. 发送邮件我们可以通过Transport的send方法来发送邮件。

如果发送成功,就可以将邮件同时抄送给指定的收件人。

三、Java Mail抄送的注意事项在使用Java Mail进行抄送时,需要注意以下几点:1. 确保收件人和抄送人的邮箱地址是正确的,避免邮件发送失败。

2. 尽量避免在邮件中插入任何网络地址,以免引起安全问题。

3. 邮件内容要简洁明了,不得包含数学公式或计算公式,以免引起阅读困扰。

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

java发送email一般步骤

java发送email一般步骤

java发送email⼀般步骤java发送email⼀般步骤⼀、引⼊javamail的jar包:⼆、创建⼀个测试类,实现将要发送的邮件内容写⼊到计算机本地,查看是否能够将内容写⼊:public static void main(String[] args) throws Exception {// 1. 创建⼀封邮件Properties props = new Properties(); // ⽤于连接邮件服务器的参数配置(发送邮件时才需要⽤到)Session session= Session.getDefaultInstance(props); // 根据参数配置,创建会话对象(为了发送邮件准备的)MimeMessage message = new MimeMessage(session); // 创建邮件对象/** 也可以根据已有的eml邮件⽂件创建 MimeMessage 对象* MimeMessage message = new MimeMessage(session, new FileInputStream("MyEmail.eml"));*/// 2. From: 发件⼈// 其中 InternetAddress 的三个参数分别为: 邮箱, 显⽰的昵称(只⽤于显⽰, 没有特别的要求), 昵称的字符集编码// 真正要发送时, 邮箱必须是真实有效的邮箱。

message.setFrom(new InternetAddress("123456@", "USER_AA", "UTF-8"));// 3. To: 收件⼈message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("123654@", "USER_CC", "UTF-8")); // To: 增加收件⼈(可选)//message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress("dd@", "USER_DD", "UTF-8")); // Cc: 抄送(可选)//message.setRecipient(, new InternetAddress("ee@", "USER_EE", "UTF-8")); // Bcc: 密送(可选)//message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress("ff@", "USER_FF", "UTF-8")); // 4. Subject: 邮件主题message.setSubject("TEST邮件主题", "UTF-8");// 5. Content: 邮件正⽂(可以使⽤html标签)message.setContent("TEST这是邮件正⽂。

JavaMail发送邮件实例——给多人发送、抄送

JavaMail发送邮件实例——给多人发送、抄送

JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。

它是Sun发布的用来处理email的API。

它可以方便地执行一些常用的邮件传输。

我们可以基于JavaMail开发出类似于Microsoft Outlook的应用程序。

虽然JavaMail是Sun的API之一,但它目前还没有被加在标准的java开发工具包中(Java Development Kit),这就意味着你在使用前必须另外下载JavaMail文件。

JavaMail包中用于处理电子邮件的核心类是:Session,Message,Address,Authenticator,Transport,Store,Folder等。

Session定义了一个基本的邮件会话,它需要从Properties中读取类似于邮件服务器,用户名和密码等信息。

关键技术:1、MimeMessage的setRecipients方法设置邮件的收件人,其中Message.RecipientType.TO常量表示收件人类型是邮件接收者,常量表示收件人类型是抄送者,Message.RecipientType.BCC常量表示收件人的类型是密送着。

2、在调用MimeMessage的setRecipients方法时,除了可以指定收件人的类型外,还可以传入一个数组,指定多个收件人的地址。

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 MultiMailsender {/*** 发送邮件给多个接收者* @param mailInfo 带发送邮件的信息* @return*/public static boolean sendMailtoMultiReceiver(MultiMailSenderInfo mailInfo){ MyAuthenticator authenticator = null;if (mailInfo.isValidate()) {authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());}Session sendMailSession = Session.getInstance(mailInfo.getProperties(), authenticator);try {Message mailMessage = new MimeMessage(sendMailSession);// 创建邮件发送者地址Address from = new InternetAddress(mailInfo.getFromAddress());mailMessage.setFrom(from);// 创建邮件的接收者地址,并设置到邮件消息中Address[] tos = null;String[] receivers = mailInfo.getReceivers();if (receivers != null){// 为每个邮件接收者创建一个地址tos = new InternetAddress[receivers.length + 1];tos[0] = new InternetAddress(mailInfo.getToAddress());for (int i=0; i<receivers.length; i++){tos[i+1] = new InternetAddress(receivers[i]);}} else {tos = new InternetAddress[1];tos[0] = new InternetAddress(mailInfo.getToAddress());}// 将所有接收者地址都添加到邮件接收者属性中mailMessage.setRecipients(Message.RecipientType.TO, tos);mailMessage.setSubject(mailInfo.getSubject());mailMessage.setSentDate(new Date());// 设置邮件内容Multipart mainPart = new MimeMultipart();BodyPart html = new MimeBodyPart();html.setContent(mailInfo.getContent(), "text/html; charset=GBK"); mainPart.addBodyPart(html);mailMessage.setContent(mainPart);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}/*** 发送带抄送的邮件* @param mailInfo 待发送邮件的消息* @returnpublic static boolean sendMailtoMultiCC(MultiMailSenderInfo mailInfo){MyAuthenticator authenticator = null;if (mailInfo.isValidate()) {authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());}Session sendMailSession = Session.getInstance(mailInfo.getProperties(), authenticator);try {Message mailMessage = new MimeMessage(sendMailSession);// 创建邮件发送者地址Address from = new InternetAddress(mailInfo.getFromAddress());mailMessage.setFrom(from);// 创建邮件的接收者地址,并设置到邮件消息中Address to = new InternetAddress(mailInfo.getToAddress());mailMessage.setRecipient(Message.RecipientType.TO, to);// 获取抄送者信息String[] ccs = mailInfo.getCcs();if (ccs != null){// 为每个邮件接收者创建一个地址Address[] ccAdresses = new InternetAddress[ccs.length];for (int i=0; i<ccs.length; i++){ccAdresses[i] = new InternetAddress(ccs[i]);}// 将抄送者信息设置到邮件信息中,注意类型为 mailMessage.setRecipients(, ccAdresses);}mailMessage.setSubject(mailInfo.getSubject());mailMessage.setSentDate(new Date());// 设置邮件内容Multipart mainPart = new MimeMultipart();BodyPart html = new MimeBodyPart();html.setContent(mailInfo.getContent(), "text/html; charset=GBK"); mainPart.addBodyPart(html);mailMessage.setContent(mainPart);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}public static void main(String[] args) {// 创建邮件信息MultiMailSenderInfo mailInfo = new MultiMailSenderInfo();mailInfo.setMailServerHost("");mailInfo.setMailServerPort("25");mailInfo.setValidate(true);mailInfo.setUserName("***");mailInfo.setPassword("***");mailInfo.setFromAddress("***@");mailInfo.setToAddress("***@");mailInfo.setSubject("MyMail测试");mailInfo.setContent("我的邮件测试/n/rMy test mail/n/r");String[] receivers = new String[]{"***@", "***@"}; String[] ccs = receivers;mailInfo.setReceivers(receivers);mailInfo.setCcs(ccs);MultiMailsender.sendMailtoMultiReceiver(mailInfo);MultiMailsender.sendMailtoMultiCC(mailInfo);}/*** 发送多接收者类型邮件的基本信息*/public static class MultiMailSenderInfo extends MailSenderInfo{// 邮件的接收者,可以有多个private String[] receivers;// 邮件的抄送者,可以有多个private String[] ccs;public String[] getCcs() {return ccs;}public void setCcs(String[] ccs) {s = ccs;}public String[] getReceivers() {return receivers;}public void setReceivers(String[] receivers) { this.receivers = receivers;}}}。

SpringBoot中利用JavaMailSender发送邮件的方法示例(附源码)

SpringBoot中利用JavaMailSender发送邮件的方法示例(附源码)

SpringBoot中利⽤JavaMailSender发送邮件的⽅法⽰例(附源码)快速⼊门在Spring Boot的⼯程中的pom.xml中引⼊spring-boot-starter-mail依赖:<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>如其他⾃动化配置模块⼀样,在完成了依赖引⼊之后,只需要在application.properties中配置相应的属性内容。

下⾯我们以QQ邮箱为例,在application.properties中加⼊如下配置(注意替换⾃⼰的⽤户名和密码):spring.mail.host=ername=⽤户名spring.mail.password=密码spring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=truespring.mail.properties.mail.smtp.starttls.required=true通过单元测试来实现⼀封简单邮件的发送:@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = Application.class)public class ApplicationTests {@Autowiredprivate JavaMailSender mailSender;@Testpublic void sendSimpleMail() throws Exception {SimpleMailMessage message = new SimpleMailMessage();message.setFrom("dyc87112@");message.setTo("dyc87112@");message.setSubject("主题:简单邮件");message.setText("测试邮件内容");mailSender.send(message);}}到这⾥,⼀个简单的邮件发送就完成了,运⾏⼀下该单元测试,看看效果如何?“由于Spring Boot的starter模块提供了⾃动化配置,所以在引⼊了spring-boot-starter-mail依赖之后,会根据配置⽂件中的内容去创建JavaMailSender实例,因此我们可以直接在需要使⽤的地⽅直接@Autowired来引⼊邮件发送对象。

JAVA实现邮件抄送,密送,多个附件发送

JAVA实现邮件抄送,密送,多个附件发送

JAVA实现邮件抄送,密送,多个附件发送以下代码在本地环境可以测试成功,假如部署到服务器上,⽆法运⾏成功,因为必须使⽤SSL,端⼝号为465。

所以需要将此处修改为经过测试,邮件发送成功//原⽂链接:/blog/2212309//需要下载mail.jar 地址:/technetwork/java/index-138643.html //简单调试⼀下可⽤,替换⼀下邮箱和授权码,邮箱密码是授权码,详情百度。

import java.io.File;import java.io.UnsupportedEncodingException;import java.util.Date;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.internet.MimeUtility;/*** 邮件多⼈发送,可设置发送,抄送,密送** @author zhutongyu**/public class SendMail {private static SendMail instance = null;private SendMail() {}public static SendMail getInstance() {if (instance == null) {instance = new SendMail();}return instance;}public void send(String to[], String cs[], String ms[], String subject,String content, String formEmail, String fileList[]) {try {Properties p = new Properties(); // Properties p =// System.getProperties();p.put("mail.smtp.auth", "true");p.put("mail.transport.protocol", "smtp");p.put("mail.smtp.host", "");p.put("mail.smtp.port", "25");// 建⽴会话Session session = Session.getInstance(p);Message msg = new MimeMessage(session); // 建⽴信息BodyPart messageBodyPart = new MimeBodyPart();Multipart multipart = new MimeMultipart();msg.setFrom(new InternetAddress(formEmail)); // 发件⼈String toList = null;String toListcs = null;String toListms = null;// 发送,if (to != null) {toList = getMailList(to);InternetAddress[] iaToList = new InternetAddress().parse(toList);msg.setRecipients(Message.RecipientType.TO, iaToList); // 收件⼈}// 抄送if (cs != null) {toListcs = getMailList(cs);InternetAddress[] iaToListcs = new InternetAddress().parse(toListcs);msg.setRecipients(, iaToListcs); // 抄送⼈ }// 密送if (ms != null) {toListms = getMailList(ms);InternetAddress[] iaToListms = new InternetAddress().parse(toListms);msg.setRecipients(Message.RecipientType.BCC, iaToListms); // 密送⼈ }msg.setSentDate(new Date()); // 发送⽇期msg.setSubject(subject); // 主题msg.setText(content); // 内容// 显⽰以html格式的⽂本内容messageBodyPart.setContent(content, "text/html;charset=gbk");multipart.addBodyPart(messageBodyPart);// 2.保存多个附件if (fileList != null) {addTach(fileList, multipart);}msg.setContent(multipart);// 邮件服务器进⾏验证Transport tran = session.getTransport("smtp");tran.connect("", "postmaster@","asiamedia");tran.sendMessage(msg, msg.getAllRecipients()); // 发送System.out.println("邮件发送成功");} catch (Exception e) {e.printStackTrace();}}// 添加多个附件public void addTach(String fileList[], Multipart multipart)throws MessagingException, UnsupportedEncodingException {for (int index = 0; index < fileList.length; index++) {MimeBodyPart mailArchieve = new MimeBodyPart();FileDataSource fds = new FileDataSource(fileList[index]);mailArchieve.setDataHandler(new DataHandler(fds));mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"GBK", "B"));multipart.addBodyPart(mailArchieve);}}private String getMailList(String[] mailArray) {StringBuffer toList = new StringBuffer();int length = mailArray.length;if (mailArray != null && length < 2) {toList.append(mailArray[0]);} else {for (int i = 0; i < length; i++) {toList.append(mailArray[i]);if (i != (length - 1)) {toList.append(",");}}}return toList.toString();}public static void main(String args[]) {SendMail send = SendMail.getInstance();String to[] = { "zhutongyu@" };String cs[] = null;String ms[] = null;String subject = "测试⼀下";String content = "这是邮件内容,仅仅是测试,不需要回复";String formEmail = "zhutongyu@";String[] arrArchievList = new String[4];arrArchievList[0] = "c:\\2012052914033429140297.rar";arrArchievList[1] = "c:\\topSearch.html";arrArchievList[2] = "c:\\topSearch2.html";arrArchievList[3] = "c:\\logo_white.png";// 2.保存多个附件send.send(to, cs, ms, subject, content, formEmail, arrArchievList); }}。

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

java发送邮件 实例

java发送邮件需要下载一个Mail.jar包MailSenderInfo.javapackage com.util.mail;/** *//*** 发送邮件需要使用的基本信息*author by wangfun 小说520*/import java.util.Properties;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[] 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 boolean isValidate() {return validate;}public void setValidate(boolean validate) {this.validate = validate;}public String[] getAttachFileNames() {return attachFileNames;}public void setAttachFileNames(String[] fileNames) { this.attachFileNames = fileNames;}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;}}MyAuthenticator.javapackage com.util.mail;import javax.mail.*;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);}}SimpleMailSender.javapackage com.util.mail;import java.util.Date;import java.util.Properties;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;/** *//*** 简单邮件(不带附件的邮件)发送器 BT下载*/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,authenticat or);try {// 根据session创建一个邮件消息Message mailMessage = new MimeMessage(sendMailSession);// 创建邮件发送者地址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());// 设置邮件消息的主要内容String mailContent = mailInfo.getContent();mailMessage.setText(mailContent);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}/*** 以HTML格式发送邮件* @param mailInfo 待发送的邮件信息*/public static boolean sendHtmlMail(MailSenderInfo mailInfo){ // 判断是否需要身份认证MyAuthenticator authenticator = null;Properties pro = mailInfo.getProperties();//如果需要身份认证,则创建一个密码验证器if (mailInfo.isValidate()) {authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo. getPassword());}// 根据邮件会话属性和密码验证器构造一个发送邮件的sessionSession sendMailSession = Session.getDefaultInstance(pro,authenticat or);try {// 根据session创建一个邮件消息Message mailMessage = new MimeMessage(sendMailSession);// 创建邮件发送者地址Address from = new InternetAddress(mailInfo.getFromAddress());// 设置邮件消息的发送者mailMessage.setFrom(from);// 创建邮件的接收者地址,并设置到邮件消息中Address to = new InternetAddress(mailInfo.getToAddress());// Message.RecipientType.TO属性表示接收者的类型为TOmailMessage.setRecipient(Message.RecipientType.TO,to);// 设置邮件消息的主题mailMessage.setSubject(mailInfo.getSubject());// 设置邮件消息发送的时间mailMessage.setSentDate(new Date());// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象Multipart mainPart = new MimeMultipart();// 创建一个包含HTML内容的MimeBodyPartBodyPart html = new MimeBodyPart();// 设置HTML内容html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");mainPart.addBodyPart(html);// 将MiniMultipart对象设置为邮件内容mailMessage.setContent(mainPart);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}}test.javapackage com.util.mail;public class test {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stub//这个类主要是设置邮件MailSenderInfo mailInfo = new MailSenderInfo();mailInfo.setMailServerHost("");mailInfo.setMailServerPort("25");mailInfo.setValidate(true);mailInfo.setUserName("yanyuanyuan101@");mailInfo.setPassword("100982");//您的邮箱密码mailInfo.setFromAddress("yanyuanyuan101@");// mailInfo.setToAddress("315905059@");mailInfo.setToAddress("msn.leonard@");mailInfo.setSubject("设置邮箱标题如 中国桂花网");mailInfo.setContent("设置邮箱内容如 中国桂花网是中国最大桂花网站==");//这个类主要来发送邮件SimpleMailSender sms = new SimpleMailSender();sms.sendTextMail(mailInfo);//发送文体格式sms.sendHtmlMail(mailInfo);//发送html格式}}posted on 2010-08-19 15:40 leonard2010阅读(37) 评论(0)编辑收藏。

java实现两个电脑发送邮件功能的方法

java实现两个电脑发送邮件功能的方法

java实现两个电脑发送邮件功能的方法Java是一种广泛应用于开发各种应用程序的编程语言,它具有跨平台性和丰富的库函数支持。

在Java中,我们可以使用JavaMail API来实现电子邮件的发送功能。

本文将介绍如何使用JavaMail API在两台电脑之间发送电子邮件。

1. 配置JavaMail API库要使用JavaMail API,我们首先需要下载并配置相应的库。

可以从Oracle 官方网站上下载JavaMail API的最新版本。

下载后,将压缩文件解压并将其中的JAR文件添加到Java项目的类路径中。

2. 创建JavaMail会话在Java中,我们需要通过创建一个JavaMail会话来连接到电子邮件服务器。

会话对象负责与服务器进行通信并发送邮件。

我们可以使用javax.mail.Session类来创建一个JavaMail会话。

以下是创建会话的代码片段:javaProperties properties = new Properties();properties.put("mail.smtp.host", "邮件服务器地址"); properties.put("mail.smtp.port", "邮件服务器端口");Session session = Session.getInstance(properties);在上述代码中,我们使用了Properties类来设置会话的属性。

我们需要指定邮件服务器的地址和端口号。

3. 创建电子邮件消息在发送电子邮件之前,我们需要创建一个javax.mail.Message对象,用于存储电子邮件的内容和详细信息。

以下是创建消息的代码片段:javaMessage message = new MimeMessage(session);message.setFrom(new InternetAddress("发件人邮箱地址")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("收件人邮箱地址"));message.setSubject("[java实现两个电脑发送邮件功能的方法]"); message.setText("邮件内容");在上述代码中,我们使用了MimeMessage类实现了javax.mail.Message接口。

Java发送邮件

Java发送邮件

Java 发送使用Java应用程序发送E-mail十分简单,但是首先你应该在你的机器上安装JavaMail API 和Java Activation Framework (JAF) 。

•您可以从Java 下载最新版本的JavaMail,翻开网页右侧有个Downloads,点击它下载。

•您可以从Java 下载最新版本的JAF〔版本1.1.1〕。

你也可以使用本站提供的下载:•JavaMail mail.jar 1.4.5••JAF〔版本1.1.1〕activation.jar•下载并解压缩这些文件,在新创立的顶层目录中,您会发现这两个应用程序的一些jar 文件。

您需要把mail.jar和activation.jar文件添加到您的CLASSPATH 中。

如果你使用第三方效劳器如QQ的SMTP效劳器,可查看文章底部用户认证完整的实例。

发送一封简单的E-mail下面是一个发送简单E-mail的例子。

假设你的localhost已经连接到网络。

// 收件人电子String to = "abcdgmail.";// 发件人电子String from = "webgmail.";// 指定发送的主机为localhostString host = "localhost";// 获取系统属性Properties properties = System.getProperties();// 设置效劳器properties.setProperty("mail.smtp.host", host);// 获取默认session对象Session session = Session.getDefaultInstance(properties);try{// 创立默认的MimeMessage 对象MimeMessage message = new MimeMessage(session);// Set From: 头部头字段message.setFrom(new InternetAddress(from));// Set To: 头部头字段message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));// Set Subject: 头部头字段message.setSubject("This is the Subject Line!");// 设置消息体message.setText("This is actual message");// 发送消息Transport.send(message);System.out.println("Sent message successfully....");}catch (MessagingException mex) {mex.printStackTrace();}}}编译并运行这个程序来发送一封简单的E-mail:如果你想发送一封给多个收件人,那么使用下面的方法来指定多个收件人ID:下面是对于参数的描述:•type:要被设置为TO, CC 或者BCC. 这里CC 代表抄送、BCC 代表秘密抄送y. 举例:Message.RecipientType.TO•addresses:这是email ID的数组。

java实现邮件发送

java实现邮件发送

java实现邮件发送本⽂实例为⼤家分享了java实现邮件发送的具体代码,供⼤家参考,具体内容如下1.使⽤socket通信功能实现java的邮件传输1.1 什么是socetSocket的英⽂原义是“孔”或“插座”。

在⽹络编程中,⽹络上的两个程序通过⼀个双向的通信连接实现数据的交换,这个连接的⼀端称为⼀个socket。

Socket套接字是通信的基⽯,是⽀持TCP/IP协议的⽹络通信的基本操作单元。

它是⽹络通信过程中端点的抽象表⽰,包含进⾏⽹络通信必须的五种信息:连接使⽤的协议,本地主机的IP地址,本地进程的协议端⼝,远地主机的IP地址,远地进程的协议端⼝。

Socket本质是编程接⼝(API),对TCP/IP的封装,TCP/IP也要提供可供程序员做⽹络开发所⽤的接⼝,这就是Socket编程接⼝;HTTP是轿车,提供了封装或者显⽰数据的具体形式;Socket是发动机,提供了⽹络通信的能⼒。

1.2.Socket的原理Socket实质上提供了进程通信的端点。

进程通信之前,双⽅⾸先必须各⾃创建⼀个端点,否则是没有办法建⽴联系并相互通信的。

正如打电话之前,双⽅必须各⾃拥有⼀台电话机⼀样套接字之间的连接过程可以分为三个步骤:服务器监听,客户端请求,连接确认。

1、服务器监听:是服务器端套接字并不定位具体的客户端套接字,⽽是处于等待连接的状态,实时监控⽹络状态。

2、客户端请求:是指由客户端的套接字提出连接请求,要连接的⽬标是服务器端的套接字。

为此,客户端的套接字必须⾸先描述它要连接的服务器的套接字,指出服务器端套接字的地址和端⼝号,然后就向服务器端套接字提出连接请求。

3、连接确认:是指当服务器端套接字监听到或者说接收到客户端套接字的连接请求,它就响应客户端套接字的请求,建⽴⼀个新的线程,把服务器端套接字的描述发给客户端,⼀旦客户端确认了此描述,连接就建⽴好了。

⽽服务器端套接字继续处于监听状态,继续接收其他客户端套接字的连接请求。

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 解析mail 抄送

java 解析mail 抄送

java 解析mail 抄送如果你想要在 Java 中解析电子邮件中的 "抄送"(CC)部分,你可以使用Java Mail API。

下面是一个简单的示例,展示如何使用 Java Mail API 来解析一个 MIME 格式的电子邮件,并提取 "抄送" 部分:```javaimport ;import ;import ;public class EmailCCExtractor {public static void main(String[] args) throws MessagingException { // 假设邮件存储在 "" 这个文件夹中,邮件地址是 "",密码是 "your-password"String host = "";String username = "";String password = "your-password";String emailId = username; // 使用你的邮件地址Properties properties = new Properties();("", "imap");("", host);("", "993"); // 使用 IMAP 的端口号("", "true"); // 启用 SSL// 创建会话对象Session session = (properties, null);Store store = ("imap");(username, password);// 获取收件箱文件夹Folder inboxFolder = ("INBOX");(_ONLY);// 获取收件箱中的所有邮件,并遍历它们以提取抄送者 Message[] messages = ();for (Message message : messages) {// 获取邮件的主题和抄送者列表String subject = ();List<InternetAddress> ccList = 抄送Addresses(message);if (ccList != null) {for (InternetAddress cc : ccList) {("抄送者: " + ());}} else {("没有找到抄送者");}}// 关闭文件夹和会话对象(false);();}}```这个示例假设你使用的是 IMAP 协议,并且邮件存储在名为 "" 的服务器上的 "INBOX" 文件夹中。

通过Java发送邮件

通过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 }。

JavaMail发送邮件(超详细)

JavaMail发送邮件(超详细)

JavaMail发送邮件(超详细)⼀:邮件发送的基本概念 本⽂我将阐述使⽤JavaMail⽅式发送和接收Email的详细说明,本博客本着以后遇到类似的邮件发送需求可以直接把代码粘过去直接使⽤,快捷⽅便省时间,对于刚接触的JavaMail的朋友们还是把⽂章过⼀遍,虽然本⽂不是最好的,但是我可以保证你能成功发送邮件; 关于邮件还有⼀些基本知识我将在下⾯简单介绍,关于邮件发送和接收的流程可以参考1:邮件中的⼏个名词发件⼈:指的是⽤哪个邮箱进⾏发送邮件的⼈收件⼈:指的是接收发件⼈发过来邮件的⼈,代表这封邮件⾯向的读者。

可以是零个到多个。

抄送⼈:指的是发件⼈把邮件发送给收件⼈的同时并抄送⼀份发给抄送⼈;此时抄送⼈可以看到收件⼈、抄送⼈的邮箱密送⼈:指的是发件⼈把邮件发送给收件⼈的同时并抄送⼀份发给密送⼈;此时抄送⼈可以看到收件⼈、抄送⼈的邮箱,⽆法看到密送⼈的邮箱说明:抄送⼈和密送⼈⼀般⽤于项⽬组A给项⽬组B发送邮件确认流程,这时项⽬组A还要告知领导我已经把⽅案流程发送给项⽬组B了;这时我就要把流程⽅案抄送⼀份给领导,就可以⽤到抄送和密送,此邮件领导是不⽤回复的2:发送邮件的⼏种⽅式JavaMail 具体使⽤说明参考Oracle官⽹给出的API:Jakarta Mail 具体使⽤说明参考Jakarta官⽅给出的API:1:javax.*也是java标准的⼀部分,但是没有包含在标准库中,⼀般属于标准库的扩展。

通常属于某个特定领域,不是⼀般性的api。

所以以扩展的⽅式提供api,以避免jdk的标准库过⼤。

当然某些早期的javax,后来被并⼊到标准库中,所有也应该属于新版本JDK的标准库。

⽐如jmx,java5以前是以扩展⽅式提供,但是jdk5以后就做为标准库的⼀部分了,所有javax.management也是jdk5的标准库的⼀部分。

2:com.sun.*是sun的hotspot虚拟机中java.* 和javax.*的实现类。

javamail发送邮件的简单实例

javamail发送邮件的简单实例

javamail发送邮件的简单实例今天学习了一下JavaMail,javamail发送邮件确实是一个比较麻烦的问题。

为了以后使用方便,自己写了段代码,打成jar包,以方便以后使用。

呵呵以下三段代码是我的全部代码,朋友们如果想用,直接复制即可。

第一个类:MailSenderInfo.javapackage com.util.mail;/** *//*** 发送邮件需要使用的基本信息*author by wangfun 小说520*/import java.util.Properties;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[] 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 boolean isValidate() {return validate;}public void setValidate(boolean validate) {this.validate = validate;}public String[] getAttachFileNames() {return attachFileNames;}public void setAttachFileNames(String[] fileNames) { this.attachFileNames = fileNames;}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;}}第二个类:SimpleMailSender.javapackage com.util.mail;import java.util.Date;import java.util.Properties;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;/** *//*** 简单邮件(不带附件的邮件)发送器 BT下载*/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);// 创建邮件发送者地址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());// 设置邮件消息的主要内容String mailContent = mailInfo.getContent();mailMessage.setText(mailContent);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}/** *//*** 以HTML格式发送邮件* @param mailInfo 待发送的邮件信息*/public static boolean sendHtmlMail(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);// 创建邮件发送者地址Address from = new InternetAddress(mailInfo.getFromAddress());// 设置邮件消息的发送者mailMessage.setFrom(from);// 创建邮件的接收者地址,并设置到邮件消息中Address to = new InternetAddress(mailInfo.getToAddress());// Message.RecipientType.TO属性表示接收者的类型为TOmailMessage.setRecipient(Message.RecipientType.TO,to);// 设置邮件消息的主题mailMessage.setSubject(mailInfo.getSubject());// 设置邮件消息发送的时间mailMessage.setSentDate(new Date());// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象Multipart mainPart = new MimeMultipart();// 创建一个包含HTML内容的MimeBodyPartBodyPart html = new MimeBodyPart();// 设置HTML内容html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");mainPart.addBodyPart(html);// 将MiniMultipart对象设置为邮件内容mailMessage.setContent(mainPart);// 发送邮件Transport.send(mailMessage);return true;} catch (MessagingException ex) {ex.printStackTrace();}return false;}}第三个类:MyAuthenticator.javapackage com.util.mail;import javax.mail.*;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);}}下面给出使用上面三个类的代码:public static void main(String[] args){//这个类主要是设置邮件MailSenderInfo mailInfo = new MailSenderInfo();mailInfo.setMailServerHost("");mailInfo.setMailServerPort("25");mailInfo.setValidate(true);mailInfo.setUserName("han2000lei@");mailInfo.setPassword("**********");//您的邮箱密码mailInfo.setFromAddress("han2000lei@");mailInfo.setToAddress("han2000lei@");mailInfo.setSubject("设置邮箱标题如 中国桂花网");mailInfo.setContent("设置邮箱内容如 中国桂花网是中国最大桂花网站==");//这个类主要来发送邮件SimpleMailSender sms = new SimpleMailSender();sms.sendTextMail(mailInfo);//发送文体格式sms.sendHtmlMail(mailInfo);//发送html格式}最后,给出朋友们几个注意的地方:1、使用此代码你可以完成你的javamail的邮件发送功能。

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、上⾯的例⼦中,如果有附件,可对附件进⾏设置。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。

它是Sun发布的用来处理email的API。

它可以方便地执行一些常用的邮件传输。

我们可以基于JavaMail开发出类似于Microsoft Outlook的应用程序。

虽然JavaMail是Sun的API之一,但它目前还没有被加在标准的java开发工具包中(Java Development Kit),这就意味着你在使用前必须另外下载JavaMail文件。

JavaMail包中用于处理电子邮件的核心类是:Session,Message,Address,Authenticator,Transport,Store,Folder等。

Session定义了一个基本的邮件会话,它需要从Properties中读取类似于邮件服务器,用户名和密码等信息。

关键技术:1、MimeMessage的setRecipients方法设置邮件的收件人,其中Message.RecipientType.TO常量表示收件人类型是邮件接收者,常量表示收件人类型是抄送者,Message.RecipientType.BCC常量表示收件人的类型是密送着。

2、在调用MimeMessage的setRecipients方法时,除了可以指定收件人的类型外,还可以传入一个数组,指定多个收件人的地址。

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 MultiMailsender{/***发送邮件给多个接收者*@param mailInfo带发送邮件的信息*@return*/public static boolean sendMailtoMultiReceiver(MultiMailSenderInfo mailInfo){ MyAuthenticator authenticator=null;if(mailInfo.isValidate()){authenticator=new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());}Session sendMailSession=Session.getInstance(mailInfo.getProperties(),authenticator);try{Message mailMessage=new MimeMessage(sendMailSession);//创建邮件发送者地址Address from=new InternetAddress(mailInfo.getFromAddress());mailMessage.setFrom(from);//创建邮件的接收者地址,并设置到邮件消息中Address[]tos=null;String[]receivers=mailInfo.getReceivers();if(receivers!=null){//为每个邮件接收者创建一个地址tos=new InternetAddress[receivers.length+1];tos[0]=new InternetAddress(mailInfo.getToAddress());for(int i=0;i<receivers.length;i++){tos[i+1]=new InternetAddress(receivers[i]);}}else{tos=new InternetAddress[1];tos[0]=new InternetAddress(mailInfo.getToAddress());}//将所有接收者地址都添加到邮件接收者属性中mailMessage.setRecipients(Message.RecipientType.TO,tos);mailMessage.setSubject(mailInfo.getSubject());mailMessage.setSentDate(new Date());//设置邮件内容Multipart mainPart=new MimeMultipart();BodyPart html=new MimeBodyPart();html.setContent(mailInfo.getContent(),"text/html;charset=GBK");mainPart.addBodyPart(html);mailMessage.setContent(mainPart);//发送邮件Transport.send(mailMessage);return true;}catch(MessagingException ex){ex.printStackTrace();}return false;}/***发送带抄送的邮件*@param mailInfo待发送邮件的消息*@return*/public static boolean sendMailtoMultiCC(MultiMailSenderInfo mailInfo){ MyAuthenticator authenticator=null;if(mailInfo.isValidate()){authenticator=new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());}Session sendMailSession=Session.getInstance(mailInfo.getProperties(),authenticator);try{Message mailMessage=new MimeMessage(sendMailSession);//创建邮件发送者地址Address from=new InternetAddress(mailInfo.getFromAddress());mailMessage.setFrom(from);//创建邮件的接收者地址,并设置到邮件消息中Address to=new InternetAddress(mailInfo.getToAddress());mailMessage.setRecipient(Message.RecipientType.TO,to);//获取抄送者信息String[]ccs=mailInfo.getCcs();if(ccs!=null){//为每个邮件接收者创建一个地址Address[]ccAdresses=new InternetAddress[ccs.length];for(int i=0;i<ccs.length;i++){ccAdresses[i]=new InternetAddress(ccs[i]);}//将抄送者信息设置到邮件信息中,注意类型为 mailMessage.setRecipients(,ccAdresses);}mailMessage.setSubject(mailInfo.getSubject());mailMessage.setSentDate(new Date());//设置邮件内容Multipart mainPart=new MimeMultipart();BodyPart html=new MimeBodyPart();html.setContent(mailInfo.getContent(),"text/html;charset=GBK");mainPart.addBodyPart(html);mailMessage.setContent(mainPart);//发送邮件Transport.send(mailMessage);return true;}catch(MessagingException ex){ex.printStackTrace();}return false;}public static void main(String[]args){//创建邮件信息MultiMailSenderInfo mailInfo=new MultiMailSenderInfo(); mailInfo.setMailServerHost("");mailInfo.setMailServerPort("25");mailInfo.setValidate(true);mailInfo.setUserName("***");mailInfo.setPassword("***");mailInfo.setFromAddress("***@");mailInfo.setToAddress("***@");mailInfo.setSubject("MyMail测试");mailInfo.setContent("我的邮件测试/n/rMy test mail/n/r");String[]receivers=new String[]{"***@","***@"}; String[]ccs=receivers;mailInfo.setReceivers(receivers);mailInfo.setCcs(ccs);MultiMailsender.sendMailtoMultiReceiver(mailInfo); MultiMailsender.sendMailtoMultiCC(mailInfo);}/***发送多接收者类型邮件的基本信息*/public static class MultiMailSenderInfo extends MailSenderInfo{//邮件的接收者,可以有多个private String[]receivers;//邮件的抄送者,可以有多个private String[]ccs;public String[]getCcs(){return ccs;}public void setCcs(String[]ccs){s=ccs;}public String[]getReceivers(){return receivers;}public void setReceivers(String[]receivers){this.receivers=receivers;}}}。

相关文档
最新文档