In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "Java how to send mail with attachments in bulk". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "Java how to send mail with attachments in batches".
Entity class (note note)
Details of the code are as follows:
Package Email;/** parameter entity class * * / public class EmailParameter {/ / sending mailbox private String fromMailbox; / / sending mailbox password (independent mailbox enter password, 163or qq and other third-party mailboxes fill in authorization code) private String fromMailboxPWD; / / the directory path of receiving mailbox private String toMailbox; / / attachment under this machine private String enclosurePath / / mailbox host (for example, QQ Mail is smtp.qq.com, 163mailbox is smtp.163.com) private String host; / / the interval between the last email and the last email sent defaults private long sleepTime = 5000; / / the successful ID private String successTag; public String getSuccessTag () {return successTag to the local file after the email is sent successfully } public void setSuccessTag (String successTag) {this.successTag = successTag;} public String getFromMailbox () {return fromMailbox;} public void setFromMailbox (String fromMailbox) {this.fromMailbox = fromMailbox;} public String getFromMailboxPWD () {return fromMailboxPWD;} public void setFromMailboxPWD (String fromMailboxPWD) {this.fromMailboxPWD = fromMailboxPWD;} public String getToMailbox () {return toMailbox } public void setToMailbox (String toMailbox) {this.toMailbox = toMailbox;} public String getEnclosurePath () {return enclosurePath;} public void setEnclosurePath (String enclosurePath) {this.enclosurePath = enclosurePath;} public String getHost () {return host;} public void setHost (String host) {this.host = host;} public long getSleepTime () {return sleepTime } public void setSleepTime (long sleepTime) {this.sleepTime = sleepTime } @ Override public String toString () {return "EmailParameter {" + "fromMailbox='" + fromMailbox +'\'+ ", fromMailboxPWD='" + fromMailboxPWD +'\'+ ", toMailbox='" + toMailbox +'\'+ ", enclosurePath='" + enclosurePath +'\'+ " Host=' "+ host +'\'+", sleepTime= "+ sleepTime +", successTag=' "+ successTag +'\'+'}' }} implementation class
After confirming that the program is running or sending a failure report, those local messages have been sent and those local files have not been sent, I use the way to change the file name in my code. This method is convenient but has drawbacks. When the attachment file you want to send is a file that has been split into volumes, the modification of the file name will cause the file to be decompressed and extracted normally. It is recommended that you record the file name of the sent file by generating a txt file.
Details of the code are as follows:
Package Email; import com.sun.mail.util.MailSSLSocketFactory;import org.springframework.util.StringUtils; import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.*;import javax.mail.internet.*;import java.io.File;import java.util.Properties;import java.util.regex.Matcher;import java.util.regex.Pattern / * * Edit and send email Service* * / public class EmailsServiceImpl {public String sendEmails (EmailParameter parameter) {if (! this.isMailbox (parameter.getFromMailbox () {return "incorrect mailbox format";} if (! this.isMailbox (parameter.getToMailbox () {return "incorrect mailbox format" } try {/ / get mail host system properties Properties properties = System.getProperties (); / / set mail server properties.setProperty ("mail.smtp.host", parameter.getHost ()); properties.put ("mail.smtp.auth", "true"); MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory () SslSocketFactory.setTrustAllHosts (true); properties.put ("mail.smtp.ssl.enable", "true"); properties.put ("mail.smtp.ssl.socketFactory", sslSocketFactory) / / get session Session session = Session.getDefaultInstance (properties,new Authenticator () {public PasswordAuthentication getPasswordAuthentication () {/ / sender account password return new PasswordAuthentication (parameter.getFromMailbox (), parameter.getFromMailboxPWD ());}}) / / the directory path where the attachment is located File fileUrl = new File (parameter.getEnclosurePath ()); / / get all the files in the directory (you can filter the file name by using the anonymous inner class override accept () method in the .listFiles () method) File fileList [] = fileUrl.listFiles () / / messages sent int currentNum = 1; if (StringUtils.isEmpty (fileList)) {return "folder" + parameter.getEnclosurePath () + "content is empty";} for (File file: fileList) {/ / messages to be sent int surplusNum = fileList.length-currentNum / / create email MimeMessage message = new MimeMessage (session); message.setFrom (new InternetAddress (parameter.getFromMailbox (); message.addRecipient (Message.RecipientType.TO, new InternetAddress (parameter.getToMailbox (); / / name email name message.setSubject (file.getName ()) / / email text BodyPart messageBodyPart = new MimeBodyPart (); String text=String.format ("Total% s messages will be sent this time -% s sent -% s sent-to be sent% s", fileList.length,currentNum,surplusNum); messageBodyPart.setText (text); / / message content Multipart multipart = new MimeMultipart () / / put the message text into the message content multipart.addBodyPart (messageBodyPart); / / email attachment messageBodyPart = new MimeBodyPart (); DataSource source = new FileDataSource (file); messageBodyPart.setDataHandler (new DataHandler (source)) / / name the attachment messageBodyPart.setFileName (MimeUtility.encodeText (file.getName (); / / put the attachment into the message content multipart.addBodyPart (messageBodyPart); / / put the message content into the message message.setContent (multipart) / / send Transport.send (message) / append the local file name as an attachment with a success flag after it is sent successfully to prevent the sending email from being unable to distinguish between sent and unsent after the program terminates unexpectedly (distinguish the order of batches by timestamp and currentNum) File newFileName = newFile (file.getParent () + File.separator + String.format ("% s_%s_%s", parameter.getSuccessTag (), currentNum) File.getName ()) File.renameTo (newFileName); currentNum++; System.out.println (text+ "| sent files:" + file.getName ()); / / increase time hash to prevent Thread.sleep (parameter.getSleepTime ()) from being detected as spam by third-party mailbox systems }} catch (Exception e) {e.printStackTrace ();} return "sent successfully" } / / mailbox verification public boolean isMailbox (String mailbox) {String check = "^ ([a-z0-9A-Z] + [- |\.]?) + [a-z0-9A-Z] @ ([a-z0-9A-Z] + (- [a-z0-9A-Z] +)?\.) + [a-zA-Z] {2,} $"; Pattern regex = Pattern.compile (check) Matcher matcher = regex.matcher (mailbox); boolean result = matcher.matches (); return result;}} method, details are as follows: package Email; public class Email {public static void main (String [] args) throws Exception {EmailParameter emailParameter = new EmailParameter (); emailParameter.setFromMailbox ("* @ 163.com"); emailParameter.setFromMailboxPWD ("*") EmailParameter.setToMailbox ("* @ qq.com"); emailParameter.setEnclosurePath ("C:\\ Users\\ ly\\ Desktop\\ email"); emailParameter.setHost ("smtp.163.com"); emailParameter.setSleepTime (5000); emailParameter.setSuccessTag ("ss"); System.out.println (new EmailsServiceImpl (). SendEmails (emailParameter)) }} Thank you for your reading, the above is the content of "how to send mail with attachments in batch by Java". After the study of this article, I believe you have a deeper understanding of how Java can send mail with attachments in batches, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.