In Java javamail sends mail with attachments

  • 2020-04-01 03:37:43
  • OfStack

This article illustrates the implementation of javamail's mail with attachments in Java. Share with you for your reference. Specific analysis is as follows:

JavaMail, as its name implies, provides developers with a programming interface for handling E-mail. It is an API published by Sun for handling email. It makes it easy to perform common mail transfers, and JavaMail is optional, so you'll need to download it from the Java web first if you need to use it. The latest version is JavaMail1.5.0, so let's take a look at an example of javamail sending mail with attachments

Mail. Java code:

package mail;  
 
import java.util.* ; 
import java.io.* ; 
import javax.mail.* ; 
import javax.mail.internet.* ; 
import javax.activation.* ; 
public class Mail { 
    //Define sender, recipient, SMTP server, username, password, subject, content, etc. < br / >     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; //Whether the server needs authentication & NBSP; < br / >     private String filename=""; 
    private Vector file = new Vector(); //
collection to save the file name of the sent attachment     
    /**
     * Set up the SMTP Server address
     */ 
    public void setSmtpServer(String smtpServer){ 
        this.smtpServer=smtpServer; 
    } 
    
    /**
     * Set the sender's address
     */ 
    public void setFrom(String from){ 
        this.from=from; 
    } 
    /**
     * Set the name of the display
     */ 
    public void setDisplayName(String displayName){ 
        this.displayName=displayName; 
    } 
    
    /**
     * Set whether the server requires authentication
     */ 
    public void setIfAuth(boolean ifAuth){ 
        this.ifAuth=ifAuth; 
    } 
    
    /**
     * Set up the E-mail The user name
     */ 
    public void setUserName(String username){ 
        this.username=username; 
    } 
    
    /**
     * Set up the E-mail password
     */ 
    public void setPassword(String password){ 
        this.password=password; 
    } 
    
    /**
     * Set receiver
     */ 
    public void setTo(String to){ 
        this.to=to; 
    } 
    
    /**
     * Set the theme
     */ 
    public void setSubject(String subject){ 
        this.subject=subject; 
    } 
    
    /**
     * Set body content
     */ 
    public void setContent(String content){ 
        this.content=content; 
    } 
    
    /**
     * This method is used to collect attachment names
     */ 
    public void addAttachfile(String fname){ 
        file.addElement(fname); 
    } 
    
    public Mail(){ 
        
    } 
    
    /**
     * Initialize the SMTP Server address, sender E-mail Address, username, password, receiver, subject, content
     */ 
    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; 
        this.username=username; 
        this.password=password; 
        this.to=to; 
        this.subject=subject; 
        this.content=content; 
    } 
    
    /**
     * Initialize the SMTP Server address, sender E-mail Address, receiver, subject, content
     */ 
    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; 
    } 
 
    /**
     * Send E-mail
     */ 
    public HashMap send(){ 
        HashMap map=new HashMap(); 
        map.put("state", "success"); 
        String message=" Email sent successfully! "; 
        Session session=null; 
        Properties props = System.getProperties(); 
        props.put("mail.smtp.host", smtpServer); 
        if(ifAuth){ //Server requires authentication & NBSP; < br / >             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()){//Accessories   < br / >                 Enumeration efile=file.elements(); 
                while(efile.hasMoreElements()){  
                    mbp=new MimeBodyPart(); 
                    filename=efile.nextElement().toString(); //Choose the name of each attachment & NBSP; < br / >                     FileDataSource fds=new FileDataSource(filename); //Getting the data source & NBSP; < br / >                     mbp.setDataHandler(new DataHandler(fds)); //Receive the attachment itself and enter it into the BodyPart  < br / >                     mbp.setFileName(fds.getName());  //Get the same file name into the BodyPart  < br / >                     mp.addBodyPart(mbp); 
                }   
                file.removeAllElements();     
            }  
            msg.setContent(mp); //Multipart added to letter & cake; < br / >             msg.setSentDate(new Date());     //Set the sending date & NBSP; of the header; < br / >             //Sending a letter & NBSP; < br / >             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=" Email failed! Error reason: n"+" Authentication error !"; 
             e.printStackTrace();  
        }catch (MessagingException e) { 
             message=" Email failed! Error reason: 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 prompt message :"+message);   < br / >         map.put("message", message); 
        return map; 
    } 
}

SmtpAuth. Java code:
package mail;  
 
public class SmtpAuth extends javax.mail.Authenticator {  
    private String username,password;  
 
    public SmtpAuth(String username,String password){  
        this.username = username;   
        this.password = password;   
    }  
    protected javax.mail.PasswordAuthentication getPasswordAuthentication() {  
        return new javax.mail.PasswordAuthentication(username,password);
    }  
}

The problem is that all the emails sent to 163 are marked with an attachment. Whether the attachment is sent or not, interested friends can improve and improve it.

I hope this article has been helpful to your Java programming.


Related articles: