1、ツール放射メールを呼び出します*
@SuppressWarnings(「ヌル」)
プライベート無効getSendEmailStartus(RequestInfoをRequestInfoを)がスロー例外{
String型のアカウント= XXXXX; //登录账户
文字列のパスワード= XXXXXXX; //登录密码
//抄送者账号
文字列CSZ = XXXXX。
ストリングrequestid = requestInfo.getRequestid()。
FormtableMain19は見つける= DB.conn()(FormtableMain19.class、「REQUESTID =?」、requestid)を見つけます。
//附件名称
文字列[] fileNameに= NULL;
//附件地址
のString [] fileSrc = NULL;
IF(!= NULL見つける。){
文字列[] fjsc =新しいString [] {「123456C1」、「123456C2」、「123456C3」}。
(fjsc.length> 0){もし
fileSrc =新しいString [fjsc.length]。
fileNameに=新しいString [fjsc.length]。
{(I ++; I <fjsc.length iが0 = INT)のために
Find2 = DB.conn EmailPDF()検索(EmailPDF.class、 "fileuniqueidentifier =?"、Fjsc [I]);.
[I] = find2.getImagefilename()ファイル名;
filesrc [I] = find2.getFilerealpath();
}
}
IF(CustomUtil.isBlank(find.getYjll())){
スロー新しい新規のRuntimeException( "メッセージを空にすることはできません、requestIdがある:" + RequestID);
}
IF(CustomUtil.isBlank(find.getYxdz())){
スロー新しいのRuntimeException( "メールアドレスは空にすることはできません、requestIdは:" + requestID);
}
IF {(SendEmailUtil.isMailAddr(find.getYxdz())!)
スロー新しいのRuntimeException( "メールアドレス入力されたが、有効ではありません、requestIdは:" + RequestID);
}
新しい新SendEmailUtil()送信(アカウント、 "XXX:"。+ find.getXm()、find.getYjll()、find.getYxdz()+ "" + CSZ、
filesrc、アカウント、パスワードは、ファイル名) ;
}
}
プロフィール*
#メールサービスの設定
email.host = xxxxx.xxx.163.com#ドメイン人々
email.prot = ***#ポート
email.protocol = IMAP#協定
#-mailアカウント、パスワード
devEmail.ACCOUNT = ******* *****
devEmail.PWSSWORD = *************
メールツール*
プライベート静的ロガーロガー= Logger.getLogger(SendEmailUtil.class)。
プライベート静的バイト[] ZIP_HEADER_1新しいバイト= [] {80、75、3、4}。
プライベート静的バイト[] ZIP_HEADER_2新しいバイト= [] {80、75、5、6}。
静的{
するSystem.setProperty(「mail.mime.splitlongparameters」、「偽」)。
するSystem.setProperty(「mail.mime.charset」、「UTF-8」);
}
public static Session initProperties(String account, String password) {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", PropUtil.getStringCK("ecustom", "email.protocol"));
properties.setProperty("mail.smtp.host", PropUtil.getStringCK("ecustom", "email.host"));
properties.setProperty("mail.smtp.port", PropUtil.getStringCK("ecustom", "email.prot"));
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory mailSSLSocketFactory = null;
try {
mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
properties.put("mail.smtp.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.socketFactory.port", PropUtil.getStringCK("ecustom", "email.prot"));
存在session问题:
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(account, password);
}
});
第二种:
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(account, password);
}
});
session.setDebug(true);
return session;
}
知識を展開します。
問題解決、
セッションsession = Session.getDefaultInstance(MYAUTH小道具、 );
変更
セッションsession = Session.getInstance(MYAUTH小道具、 );
することができます
私は、再実行し、法に少しコードを置き換えるために彼の方法に従ってください正常に送信され、最初のメールアカウントとパスワードを入力し、第二の入力、他のメールアカウントとパスワード、ポイントを送って、[OK]を、成功しました。
さて、問題はここで解決しますが、Session.getDefaultInstanceとSession.getInstance何の違いを理解していない、それは作るのですか?そして、統計を見て、結果はまた、553個の異常がブログを書く人に遭遇した、実際に彼のブログのタイトルです:
「Session.getDefaultInstanceアプリケーションでのJavaMail」、
一般的な、見つけるのはそれほど難しいことではありませんこれを検索します検索の問題、の名前です。ポスターは、問題のタイトルを変更することができるなら、私は上のように見てする必要はありません。しかし、まだ彼は方法は、あなたがこのポスト553の異常の第二の発生をログに記録する他の電子メールアカウントを入力したときにSession.getDefaultInstanceが表示されます使用理由を詳細に説明して、この男に感謝したいと思います。
以下は、この記事からの抜粋です:
http://muder2007.blog.163.com/blog/static/45933070200872025130613/
何getDefaultInstance?
最初のプロパティが存在する存在する場合、キャッシュから、プロセスフローから分かるように
本発明は、デフォルトのプロパティがロードされた場合に
、ユーザによって定義されたプロパティをロードのみが存在する場合
の特性を作成するために、ユーザーごとにそうするとき、別のアプリケーション、または、のgetInstanceを呼び出す必要があり
ますが、デフォルトのプロパティを使用するユーザーを許可したい場合を除き
それは最初に私がページに何回かデータを変更するので、どんな性質を探すためにメモリとシステムファイルに行き、実際になりますので、問題を発見した際にバックグラウンドでセッションを生成するシステムが起動し、MailUtil.sendTextMessageので(mailSessionと同じ、RptTaskMailConfig.Sender、
レシーバー、ヌル、mail_subject、mail_content、 "2312"、NULL);送信者および受信、送信者、従って誤差が、真正Session.getDefaultInstance(小道具を)変更矛盾セッション; Session.getInstanceとして(本物の小道具、);後で、あなたは正しい口座番号、パスワードやその他の情報を送信した後に、メッセージを変更することができます.OK
最後に、の差session.getdefaultinstanceとのgetInstanceを追加します。
あなたが送信[email protected] 2#-mailを使用し、[email protected] 1#送信電子メールなどの使用など、JavaMailのを送信するために、両方のアカウントを使用したい場合は、この時間は、あなたが同時にjava.mail.Sessionを2つのオブジェクトを作成する必要があります。それでもSession.getDefaultInstanceは、セッションオブジェクトを作成し使用している場合しかし、あなたはその第二のユーザ名を検索します:セッション[email protected]が作成され、常に最初のように、これはなぜですか?ので、getDefaultInstanceは、ユーザー名とパスワードのプロパティが種類を変更することはできません最終的なものであるの内側に、本当にシングルトンである、と。だから、あなたは来る2が[email protected]して電子メールを送信されるでしょう。したがって、この時間は、あなたは、セッションオブジェクトを作成するためにjavax.mail.Session.getInstance()メソッドを使用します。
/**
* @Description: 发送邮件
* @Title: send
* @date 2019-10-08 17:12
* @param @param sender发件人别名
* @param @param subject邮件主题
* @param @param content接收者列表,多个接收者之间用","隔开
* @param @param receiverList :内容
* @param @param fileSrc []附件地址
* @return void 返回类型 fileName:[]附件名称 account: 发送者账户 password :发送者密码
* @throws @return void
* @param sender
* @param subject
* @param content
* @param receiverList
* @param fileSrc
* @throws Exception
*/
public void send(String sender, String subject, String content, String receiverList, String[] fileSrc,
String account, String password, String[] fileName) throws Exception {
Session session = initProperties(account, password);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(account, sender));// 发件人,可以设置发件人的别名
InternetAddress[] internetAddressTo = new InternetAddress().parse(receiverList);
mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo);
mimeMessage.setSubject(subject);
mimeMessage.setSentDate(new Date());
Multipart mainParth = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent(content, "text/html; charset=UTF-8");
mainParth.addBodyPart(html);
MimeBodyPart bodyPart = new MimeBodyPart();
if (fileSrc != null && fileSrc.length > 0) {
logger.info("附件数量:" + fileSrc.length);
URL url;
for (int i = 0; i < fileSrc.length; i++) {
String devAgreement =http;
if (fileSrc[i].startsWith(devAgreement)) {
logger.info("在线附件文件发送");
bodyPart = new MimeBodyPart();
url = new URL(fileSrc[i]);
DataSource dataSource = new URLDataSource(url);
DataHandler dataHandler = new DataHandler(dataSource);
bodyPart.setDataHandler(dataHandler);
mainParth.addBodyPart(bodyPart);
} else {
logger.info("附件文件发送含压缩文件");
bodyPart = new MimeBodyPart();
MimeBodyPart bodyPart2 = fileDecompression(bodyPart, fileSrc[i], fileName[i]);
mainParth.addBodyPart(bodyPart2);
logger.info("》》》退出");
}
}
}
logger.info("》》》内容进入");
mimeMessage.setContent(mainParth);
//mimeMessage.saveChanges();
logger.info("》》》发射");
Transport.send(mimeMessage);
logger.info("邮件发送结束");
}
/**
* @Description:解压服务器文件 不同服务器文件解压读取未解决
* @Title: fileDecompression
* @date 2019-11-01
* @param @param string 参数
* @return void 返回类型
* @throws @return void
* @param string
* @throws IOException
* @throws MessagingException
*/
private MimeBodyPart fileDecompression(MimeBodyPart bodyPart, String filePath, String fileName)
throws IOException, MessagingException {
logger.info("文件地址:" + filePath);
logger.info("文件名称:" + fileName);
File file = new File(filePath);
if (!file.exists()) {
fileError(file);
}
boolean archiveFile = isArchiveFile(file);
if (archiveFile) {//zip压缩包
logger.info("压缩包邮件解析发送");
DataSource ds = new FileDataSource(file);
bodyPart.setDataHandler(new DataHandler(ds));
bodyPart.setFileName(MimeUtility.encodeWord(fileName, "UTF-8", "Q"));
logger.info("压缩包邮件解析结束");
return bodyPart;
} else {// 文件
logger.info("文件发送");
DataSource ds = new FileDataSource(file);
bodyPart.setDataHandler(new DataHandler(ds));
bodyPart.setFileName(MimeUtility.encodeWord(fileName, "UTF-8", "Q"));
return bodyPart;
}
}
/**
* @Description: 抛出异常
* @Title: fileError
* @date 2019-11-05 17:48
* @param @param file 参数
* @return void 返回类型
* @throws @return void
* @param file
*/
private void fileError(File file) {
throw new RuntimeException("文件路径不正确");
}
/**
* 判断文件是否为一个压缩文件
*
* @param file
* @return
*/
public static boolean isArchiveFile(File file) {
if (file == null) {
return false;
}
if (file.isDirectory()) {
return false;
}
boolean isArchive = false;
InputStream input = null;
try {
input = new FileInputStream(file);
byte[] buffer = new byte[4];
int length = input.read(buffer, 0, 4);
if (length == 4) {
isArchive = (Arrays.equals(ZIP_HEADER_1, buffer)) || (Arrays.equals(ZIP_HEADER_2, buffer));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
}
}
}
return isArchive;
}
/**
*
* @param mailString 待判断的mail邮件地址
* @return boolean 是否匹配成功
*/
public static boolean isMailAddr(String mailString) {
String pattenString = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
Pattern pattern = Pattern.compile(pattenString);
Matcher matcher = pattern.matcher(mailString);
return matcher.matches();
}
詳しく知ることができます。
マルチパート/フォームデータ:
1、通常のキーと値のペアに提出することができる、あなたは、(複数の)ファイルのペアを提出することができます。
HTTP POST仕様の提出にのみ使用することができ、このタイプ、所属するHTTPクライアントが含まれていません(ブラウザ、JavaのHTTPClientの)延長2、Content-Typeの
図3は、通常はブラウザで形成、またはhttpクライアント(JavaのHTTPClientの)が使用されています。
アプリケーション/ octet-streamの:
1、唯一のバイナリに提出し、バイナリを提出することができ、提出された書類場合は、背景だけ一つのパラメータのみが、唯一のストリーム(またはバイト配列)を受け、書類を提出します
Content-Typeの1のHTTP仕様に属する2、
3、ほとんど使用されません
アプリケーション/ x-www-form-urlencodedで
NAME1 = VALUE1&NAME2 =値2、ポスト時間が配置されるHTTPボディ、アドレスバーに表示されたときに取得する:1は、コンテンツタイプの仕様、一般的に使用されるブラウザのフォームの送信、データ編成形式のhttpに属していません。
2、すべてのキーと値は、URLエンコードされ、のURLEncoderを参照してください。
容器に導入されたアーカイブ電子メールの配列を抽出し、バイトストリームに変換*
/ **
*根据文件路径获取ZIP字节流
* @param zipFilePath
* @return
* @throwsのIOException
* /
パブリック静的バイト[] getBytesByZip(文字列zipFilePath)はIOExceptionが{スロー
入力ストリームInputStreamを。
バイト[] fileByte = NULL;
ZIPファイルZIPファイル= NULL;
試す{
ZIPファイル=新しいZIPファイル(zipFilePath)。
<?>列挙エントリ= zipFile.getEntries();
(entries.hasMoreElements()){一方
のZipEntryエントリ=(またはZipEntry)entries.nextElement();
inputStream = zipFile.getInputStream(エントリー)。
fileByte = inputStreamToByte(のinputStream)。
inputStream.close();
}
}最後に{
IF(!zipファイル= NULL){
zipFile.close()。
}
}
fileByteを返します。
}
/**
* InputStream文件流转换成字节数组。
* @param in 文件流
* @return
* @throws IOException
*/
public static byte[] inputStreamToByte(InputStream in)
throws IOException{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int count = -1;
while((count = in.read(data, 0, 1024)) != -1) {
outStream.write(data, 0, count);
}
outStream.close();
data = null;
return outStream.toByteArray();
}
さまざまな方法で添付ファイルを送信します。
/ **
* Eメールやバイト単位で[]ストリームまたは送信電子メールの添付ファイルのbase64でエンコードされた文字列
* @paramお知らせ
* @return無効
* /
パブリック無効sendEmailByFlow(お知らせお知らせ)が例外をスロー{
ブール= sessionDebug falseに;
たInternetAddress [] =アドレスNULL;
のSimpleDateFormatてSimpleDateFormat SDF新しい新=( "MM-DD-YYYY HH:MM:SS");
試み{
SiteConfig config = new SiteConfig(); //配置信息
String mailServer = config.getSendEmailSmtp(); //服务器地址
String mailAuth = config.getMailSmtpAuth(); //验证
String mailAddress = config.getSendEmailAddress(); //邮箱
String mailUser = config.getSendEmailAddress(); //用户名
String mailPassword = config.getSendEmailPassword(); //密码
String mailSmtpPort = config.getMailSmtpPort(); //端口
Properties props = System.getProperties();
props.put("mail.smtp.host", mailServer);
props.put("mail.smtp.auth", mailAuth);
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(mailAddress));
if (notice.getToAddress() != null && !"".equals(notice.getToAddress())) {
address = InternetAddress.parse(notice.getToAddress(), false);
for (InternetAddress addr:address) {
if (this.isEmail(addr.getAddress()) == false) {
log.info(sdf.format(new Date() + notice.getScene() + addr.getAddress() + "地址格式不正确。"));
}
}
msg.setRecipients(Message.RecipientType.TO, address);
}
if (notice.getCcAddress() != null && !"".equals(notice.getCcAddress())) {
address = InternetAddress.parse(notice.getCcAddress(), false);
for (InternetAddress addr:address) {
if (this.isEmail(addr.getAddress()) == false) {
log.info(sdf.format(new Date() + notice.getScene() + addr.getAddress() + "地址格式不正确。"));
}
}
msg.setRecipients(Message.RecipientType.CC, address);
}
if (notice.getBccAddress() != null && !"".equals(notice.getBccAddress())) {
address = InternetAddress.parse(notice.getBccAddress(), false);
for (InternetAddress addr:address) {
if (this.isEmail(addr.getAddress()) == false) {
log.info(sdf.format(new Date() + notice.getScene() + addr.getAddress() + "地址格式不正确。"));
}
}
msg.setRecipients(Message.RecipientType.BCC, address);
}
String message = notice.getContent();
msg.setSubject(notice.getTitle());
msg.setSentDate(new Date());
msg.setText(message);
Multipart mm = new MimeMultipart();
BodyPart mdp = new MimeBodyPart(); //新建一个存放信件内容的BodyPart对象
mdp.setContent(message, "text/html;charset=UTF-8");
mm.addBodyPart(mdp); //将含有信件内容的BodyPart加入到MimeMultipart对象中
String[] fname = notice.getAttachFileName();
byte[] data = null;
String[] file64Str = notice.getFile64Str();
if (file64Str != null && file64Str.length > 0) {
BASE64Decoder base = new BASE64Decoder();
for (int i=0; i<fname.length; i++) {
data = base.decodeBuffer(file64Str[i]);
mdp = new MimeBodyPart();
DataSource obj = new ByteArrayDataSource(data, "application/octet-stream");
DataHandler dh = new DataHandler(obj);
mdp.setDataHandler(dh);
mdp.setFileName(MimeUtility.encodeWord(fname[i],"UTF-8","Q"));
mdp.setHeader("content-id", fname[i]);
mm.addBodyPart(mdp);
}
} else {
data = notice.getFileFlow();
mdp = new MimeBodyPart();
DataSource obj = new ByteArrayDataSource(data, "application/octet-stream");
DataHandler dh = new DataHandler(obj);
mdp.setDataHandler(dh);
mdp.setFileName(MimeUtility.encodeWord(fname[0],"UTF-8","Q"));
mdp.setHeader("content-id", fname[0]);
mm.addBodyPart(mdp);
}
msg.setContent(mm);
msg.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(mailServer, Integer.parseInt(mailSmtpPort), mailUser, mailPassword);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
log.error(sdf.format(new Date() + notice.getScene() + "异常错误,邮件发送失败。"));
throw e;
}
}
private boolean isEmail(String str) {
String regex = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
return match(regex, str);
}
private boolean match(String regex, String str) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
/**
* 根据byte数组,生成文件。
* @param filePath 目标文件路径
* @return
* @throws IOException
*/
public static void toRealFile(byte[] bfile, String filePath)
throws IOException {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
file = new File(filePath);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} finally {
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
}
}