java发邮件如何写一个JAVA类可以实现邮件发送功能,也可以实现群发功能
java发邮件 时间:2021-09-04 阅读:(
)
如何利用java发送163邮件,最好不要javamail
import?java.util.Properties;
import?javax.activation.DataHandler;
import?javax.activation.FileDataSource;
import?javax.mail.Address;
import?javax.mail.BodyPart;
import?javax.mail.Message;
import?javax.mail.Multipart;
import?javax.mail.Session;
import?javax.mail.Transport;
import?Address;
import?.MimeBodyPart;
import?.MimeMessage;
import?.MimeMultipart;
public?class?Mail?{
private?MimeMessage?mimeMsg;?//?MIME邮件对象
private?Session?session;?//?邮件会话对象
private?Properties?props;?//?系统属性
//?smtp认证用户名和密码
private?String?username;
private?String?password;
private?Multipart?mp;?//?Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
/**
?*?Constructor
?*?
?*?@param?smtp
?*????????????邮件发送服务器
?*/
public?Mail(String?smtp)?{
setSmtpHost(smtp);
createMimeMessage();
}
/**
?*?设置邮件发送服务器
?*?
?*?@param?hostName
?*????????????String
?*/
public?void?setSmtpHost(String?hostName)?{
if?(props?==?null)
props?=?System.getProperties();?//?获得系统属性对象
props.put("mail.smtp.host",?hostName);?//?设置SMTP主机
}
/**
?*?创建MIME邮件对象
?*?
?*?@return
?*/
public?boolean?createMimeMessage()?{
try?{
session?=?Session.getDefaultInstance(props,?null);?//?获得邮件会话对象
}?catch?(Exception?e)?{
System.err.println("获取邮件会话对象时发生错误!"?+?e);
return?false;
}
try?{
mimeMsg?=?new?MimeMessage(session);?//?创建MIME邮件对象
mp?=?new?MimeMultipart();
return?true;
}?catch?(Exception?e)?{
System.err.println("创建MIME邮件对象失败!"?+?e);
return?false;
}
}
/**
?*?设置SMTP是否需要验证
?*?
?*?@param?need
?*/
public?void?setNeedAuth(boolean?need)?{
if?(props?==?null)
props?=?System.getProperties();
if?(need)?{
props.put("mail.smtp.auth",?"true");
}?else?{
props.put("mail.smtp.auth",?"false");
}
}
/**
?*?设置用户名和密码
?*?
?*?@param?name
?*?@param?pass
?*/
public?void?setNamePass(String?name,?String?pass)?{
username?=?name;
password?=?pass;
}
/**
?*?设置邮件主题
?*?
?*?@param?mailSubject
?*?@return
?*/
public?boolean?setSubject(String?mailSubject)?{
try?{
mimeMsg.setSubject(mailSubject);
return?true;
}?catch?(Exception?e)?{
System.err.println("设置邮件主题发生错误!");
return?false;
}
}
/**
?*?设置邮件正文
?*?
?*?@param?mailBody
?*????????????String
?*/
public?boolean?setBody(String?mailBody)?{
try?{
BodyPart?bp?=?new?MimeBodyPart();
bp.setContent(""?+?mailBody,?"text/html;charset=utf-8");
mp.addBodyPart(bp);
return?true;
}?catch?(Exception?e)?{
System.err.println("设置邮件正文时发生错误!"?+?e);
return?false;
}
}
/**
?*?添加附件
?*?
?*?@param?filename
?*????????????String
?*/
public?boolean?addFileAffix(String?filename)?{
try?{
BodyPart?bp?=?new?MimeBodyPart();
FileDataSource?fileds?=?new?FileDataSource(filename);
bp.setDataHandler(new?DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
return?true;
}?catch?(Exception?e)?{
System.err.println("增加邮件附件:"?+?filename?+?"发生错误!"?+?e);
return?false;
}
}
/**
?*?设置发信人
?*?
?*?@param?from
?*????????????String
?*/
public?boolean?setFrom(String?from)?{
try?{
mimeMsg.setFrom(new?Address(from));?//?设置发信人
return?true;
}?catch?(Exception?e)?{
return?false;
}
}
/**
?*?设置收信人
?*?
?*?@param?to
?*????????????String
?*/
public?boolean?setTo(String?to)?{
if?(to?==?null)
return?false;
try?{
mimeMsg.setRecipients(Message.RecipientType.TO,
Address.parse(to));
return?true;
}?catch?(Exception?e)?{
return?false;
}
}
/**
?*?设置抄送人
?*?
?*?@param?copyto
?*????????????String
?*/
public?boolean?setCopyTo(String?copyto)?{
if?(copyto?==?null)
return?false;
try?{
mimeMsg.setRecipients(Message.RecipientType.CC,
(Address[])?Address.parse(copyto));
return?true;
}?catch?(Exception?e)?{
return?false;
}
}
/**
?*?发送邮件
?*/
public?boolean?sendOut()?{
try?{
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println("正在发送邮件....");
Session?mailSession?=?Session.getInstance(props,?null);
Transport?transport?=?mailSession.getTransport("smtp");
transport.connect((String)?props.get("mail.smtp.host"),?username,
password);
transport.sendMessage(mimeMsg,
mimeMsg.getRecipients(Message.RecipientType.TO));
// 如果抄送人为null??不添加抄送人
if(mimeMsg.getRecipients(Message.RecipientType.CC)?!=?null)
transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC));
//?transport.send(mimeMsg);
System.out.println("发送邮件成功!");
transport.close();
return?true;
}?catch?(Exception?e)?{
System.err.println("邮件发送失败!"?+?e);
e.printStackTrace();
return?false;
}
}
/**
?*?调用sendOut方法完成邮件发送
?*?
?*?@param?smtp
?*?@param?from
?*?@param?to
?*?@param?subject
?*?@param?content
?*?@param?username
?*?@param?password
?*?@return?boolean
?*/
public?static?boolean?send(String?smtp,?String?from,?String?to,
String?subject,?String?content,?String?username,?String?password)?{
Mail?theMail?=?new?Mail(smtp);
theMail.setNeedAuth(true);?//?需要验证
if?(!theMail.setSubject(subject))
return?false;
if?(!theMail.setBody(content))
return?false;
if?(!theMail.setTo(to))
return?false;
if?(!theMail.setFrom(from))
return?false;
theMail.setNamePass(username,?password);
if?(!theMail.sendOut())
return?false;
return?true;
}
/**
?*?调用sendOut方法完成邮件发送,带抄送
?*?
?*?@param?smtp
?*?@param?from
?*?@param?to
?*?@param?copyto
?*?@param?subject
?*?@param?content
?*?@param?username
?*?@param?password
?*?@return?boolean
?*/
public?static?boolean?sendAndCc(String?smtp,?String?from,?String?to,
String?copyto,?String?subject,?String?content,?String?username,
String?password)?{
Mail?theMail?=?new?Mail(smtp);
theMail.setNeedAuth(true);?//?需要验证
if?(!theMail.setSubject(subject))
return?false;
if?(!theMail.setBody(content))
return?false;
if?(!theMail.setTo(to))
return?false;
if?(!theMail.setCopyTo(copyto))
return?false;
if?(!theMail.setFrom(from))
return?false;
theMail.setNamePass(username,?password);
if?(!theMail.sendOut())
return?false;
return?true;
}
/**
?*?调用sendOut方法完成邮件发送,带附件
?*?
?*?@param?smtp
?*?@param?from
?*?@param?to
?*?@param?subject
?*?@param?content
?*?@param?username
?*?@param?password
?*?@param?filename
?*????????????附件路径
?*?@return
?*/
public?static?boolean?send(String?smtp,?String?from,?String?to,
String?subject,?String?content,?String?username,?String?password,
String?filename)?{
Mail?theMail?=?new?Mail(smtp);
theMail.setNeedAuth(true);?//?需要验证
if?(!theMail.setSubject(subject))
return?false;
if?(!theMail.setBody(content))
return?false;
if?(!theMail.addFileAffix(filename))
return?false;
if?(!theMail.setTo(to))
return?false;
if?(!theMail.setFrom(from))
return?false;
theMail.setNamePass(username,?password);
if?(!theMail.sendOut())
return?false;
return?true;
}
/**
?*?调用sendOut方法完成邮件发送,带附件和抄送
?*?
?*?@param?smtp
?*?@param?from
?*?@param?to
?*?@param?copyto
?*?@param?subject
?*?@param?content
?*?@param?username
?*?@param?password
?*?@param?filename
?*?@return
?*/
public?static?boolean?sendAndCc(String?smtp,?String?from,?String?to,
String?copyto,?String?subject,?String?content,?String?username,
String?password,?String?filename)?{
Mail?theMail?=?new?Mail(smtp);
theMail.setNeedAuth(true);?//?需要验证
if?(!theMail.setSubject(subject))
return?false;
if?(!theMail.setBody(content))
return?false;
if?(!theMail.addFileAffix(filename))
return?false;
if?(!theMail.setTo(to))
return?false;
if?(!theMail.setCopyTo(copyto))
return?false;
if?(!theMail.setFrom(from))
return?false;
theMail.setNamePass(username,?password);
if?(!theMail.sendOut())
return?false;
return?true;
}
public?static?void?main(String[]?args)?{
//// SMTP服务器
String?smtp?=?"xxx";
// 发信人
String?from?=?"xxx";
String?to?=?"xxx";
String?subject?=?"xxx";
String?content?=?"xxx";
String?username?=?"xxx";
String?password?=?"xxx";
Mail.send(smtp,?from,?to,?subject,?content,?username,?password);
}
}这个是我现在在用的如何写一个JAVA类可以实现邮件发送功能,也可以实现群发功能
package byd.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import .Socket;
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;
import java.util.Map;
import sun.misc.BASE64Encoder;
/**
* 该类使用Socket连接到邮件服务器, 并实现了向指定邮箱发送邮件及附件的功能。
*
* @author Kou Hongtao
*/
public class Email {
/**
* 换行符
*/
private static final String LINE_END = "
";
/**
* 值为“true”输出高度信息(包括服务器响应信息),值为“ false”则不输出调试信息。
*/
private boolean isDebug = true;
/**
* 值为“true”则在发送邮件{@link Mail#send()} 过程中会读取服务器端返回的消息,
* 并在邮件发送完毕后将这些消息返回给用户。
*/
private boolean isAllowReadSocketInfo = true;
/**
* 邮件服务器地址
*/
private String host;
/**
* 发件人邮箱地址
*/
private String from;
/**
* 收件人邮箱地址
*/
private List to;
/**
* 抄送地址
*/
private List;
/**
* 暗送地址
*/
private List ;
/**
* 邮件主题
*/
private String subject;
/**
* 用户名
*/
private String user;
/**
* 密码
*/
private String password;
/**
* MIME邮件类型
*/
private String contentType;
/**
* 用来绑定多个邮件单元{@link #partSet}
* 的分隔标识,我们可以将邮件的正文及每一个附件都看作是一个邮件单元 。
*/
private String boundary;
/**
* 邮件单元分隔标识符,该属性将用来在邮件中作为分割各个邮件单元的标识 。
*/
private String boundaryNextPart;
/**
* 传输邮件所采用的编码
*/
private String contentTransferEncoding;
/**
* 设置邮件正文所用的字符集
*/
private String charset;
/**
* 内容描述
*/
private String contentDisposition;
/**
* 邮件正文
*/
private String content;
/**
* 发送邮件日期的显示格式
*/
private String simpleDatePattern;
/**
* 附件的默认MIME类型
*/
private String defaultAttachmentContentType;
/**
* 邮件单元的集合,用来存放正文单元和所有的附件单元。
*/
private List partSet;
private List alternativeList;
private String mixedBoundary;
private String mixedBoundaryNextPart;
/**
* 不同类型文件对应的{@link MIME} 类型映射。
在添加附件
* {@link #addAttachment(String)} 时,程序会在这个映射中查找对应文件的
* {@link MIME} 类型,如果没有, 则使用
* {@link #defaultAttachmentContentType} 所定义的类型。
*/
private static Map contentTypeMap;
private static enum TextType {
PLAIN("plain"), HTML("html");
private String v;
private TextType(String v) {
this.v = v;
}
public String getValue() {
return this.v;
}
}
static {
// MIME Media Types
contentTypeMap = new HashMap();
contentTypeMap.put("xls", "application/vnd.ms-excel");
contentTypeMap.put("xlsx", "application/vnd.ms-excel");
contentTypeMap.put("xlsm", "application/vnd.ms-excel");
contentTypeMap.put("xlsb", "application/vnd.ms-excel");
contentTypeMap.put("doc", "application/msword");
contentTypeMap.put("dot", "application/msword");
contentTypeMap.put("docx", "application/msword");
contentTypeMap.put("docm", "application/msword");
contentTypeMap.put("dotm", "application/msword");
}
/**
* 该类用来实例化一个正文单元或附件单元对象,他继承了 {@link Mail}
* ,在这里制作这个子类主要是为了区别邮件单元对象和邮件服务对象 ,使程序易读一些。
* 这些邮件单元全部会放到partSet 中,在发送邮件 {@link #send()}时, 程序会调用
* {@link #getAllParts()} 方法将所有的单元合并成一个符合MIME格式的字符串。
*
* @author Kou Hongtao
*/
private class MailPart extends Email {
public MailPart() {
}
}
/**
* 默认构造函数
*/
public Email() {
defaultAttachmentContentType = "application/octet-stream";
simpleDatePattern = "yyyy-MM-dd HH:mm:ss";
boundary = "--=_NextPart_zlz_3907_" + System.currentTimeMillis();
boundaryNextPart = "--" + boundary;
contentTransferEncoding = "base64";
contentType = "multipart/mixed";
charset = Charset.defaultCharset().name();
partSet = new ArrayList();
alternativeList = new ArrayList();
to = new ArrayList();
= new ArrayList();
= new ArrayList();
mixedBoundary = "=NextAttachment_zlz_" + System.currentTimeMillis();
mixedBoundaryNextPart = "--" + mixedBoundary;
}
/**
* 根据指定的完整文件名在 {@link #contentTypeMap} 中查找其相应的MIME类型,
* 如果没找到,则返回 {@link #defaultAttachmentContentType}
* 所指定的默认类型。
*
* @param fileName
* 文件名
* @return 返回文件对应的MIME类型。
*/
private String getPartContentType(String fileName) {
String ret = null;
if (null != fileName) {
int flag = fileName.lastIndexOf(".");
if (0 <= flag && flag < fileName.length() - 1) {
fileName = fileName.substring(flag + 1);
}
ret = contentTypeMap.get(fileName);
}
if (null == ret) {
ret = defaultAttachmentContentType;
}
return ret;
}
/**
* 将给定字符串转换为base64编码的字符串
*
* @param str
* 需要转码的字符串
* @param charset
* 原字符串的编码格式
* @return base64编码格式的字符
*/
private String toBase64(String str, String charset) {
if (null != str) {
try {
return toBase64(str.getBytes(charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "";
}
/**
* 将指定的字节数组转换为base64格式的字符串
*
* @param bs
* 需要转码的字节数组
* @return base64编码格式的字符
*/
private String toBase64(byte[] bs) {
return new BASE64Encoder().encode(bs);
}
/**
* 将给定字符串转换为base64编码的字符串
*
* @param str
* 需要转码的字符串
* @return base64编码格式的字符
*/
private String toBase64(String str) {
return toBase64(str, Charset.defaultCharset().name());
}
/**
* 将所有的邮件单元按照标准的MIME格式要求合并。
*
* @return 返回一个所有单元合并后的字符串。
*/
private String getAllParts() {
StringBuilder sbd = new StringBuilder(LINE_END);
sbd.append(mixedBoundaryNextPart);
sbd.append(LINE_END);
sbd.append("Content-Type: ");
sbd.append("multipart/alternative");
sbd.append(";");
sbd.append("boundary="");
sbd.append(boundary).append("""); // 邮件类型设置
sbd.append(LINE_END);
sbd.append(LINE_END);
sbd.append(LINE_END);
addPartsToString(alternativeList, sbd, getBoundaryNextPart());
sbd.append(getBoundaryNextPart()).append("--");
sbd.append(LINE_END);
addPartsToString(partSet, sbd, mixedBoundaryNextPart);
sbd.append(LINE_END);
sbd.append(mixedBoundaryNextPart).append("--");
sbd.append(LINE_END);
// sbd.append(boundaryNextPart).
// append(LINE_END);
alternativeList.clear();
partSet.clear();
return sbd.toString();
}
卢森堡商家gcorelabs是个全球数据中心集大成的运营者,不但提供超过32个数据中心的VPS、13个数据中心的cloud(云服务器)、超过44个数据中心的独立服务器,还提供超过100个数据中心节点的CDN业务。CDN的总带宽容量超过50Tbps,支持免费测试! Gcorelabs根据业务分,有2套后台,分别是: CDN、流媒体平台、DDoS高防业务、块存储、cloud云服务器、裸金属服务器...
zji怎么样?zji最近新上韩国BGP+CN2线路服务器,国内三网访问速度优秀,适用8折优惠码zji,优惠后韩国服务器最低每月440元起。zji主机支持安装Linux或者Windows操作系统,会员中心集成电源管理功能,8折优惠码为终身折扣,续费同价,全场适用。ZJI是原Wordpress圈知名主机商:维翔主机,成立于2011年,2018年9月启用新域名ZJI,提供中国香港、台湾、日本、美国独立服...
官方网站:点击访问CDN客服QQ:123008公司名:贵州青辞赋文化传媒有限公司域名和IP被墙封了怎么办?用cloudsecre.com网站被攻击了怎么办?用cloudsecre.com问:黑客为什么要找网站来攻击?答:黑客需要找肉鸡。问:什么是肉鸡?答:被控的服务器和电脑主机就是肉鸡。问:肉鸡有什么作用?答:肉鸡的作用非常多,可以用来干违法的事情,通常的行为有:VPN拨号,流量P2P,攻击傀儡,...
java发邮件为你推荐
硬件设计方案我有一个好的设计方案,智能硬件,怎么把方案卖出去。。win10发布win10什么时候发布正式版javaHDvideo有支持AVI 或者RVMB格式的JAVA的手机视频播放器吗?什么是光纤什么是光纤?什么是宽带?两者有什么不同?开房数据库ODBC数据库是什么呢?约束是什么意思约束,是什么意思。如有回答,请详细,约束是什么意思cad软件里“推断约束是什么意思”360官网打不开360官网进不了怎么办趋势防毒趋势杀毒好用吗?分销渠道案例关于nike公司的分销渠道以及营销策略?
美国域名 韩国vps vps交流 草根过期域名 骨干网 服务器评测 便宜服务器 inmotionhosting lamp配置 刀片服务器的优势 网络空间租赁 绍兴电信 服务器硬件防火墙 我的世界服务器ip 国外的代理服务器 谷歌台湾 徐州电信 深圳主机托管 亿库 湖南铁通 更多