JavaMail Send message instance with attachment in Java

Source: Internet
Author: User
Tags auth

Mail.java Code

The code is as follows Copy 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, user name, password, subject, content, etc.
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 wants authentication
Private String filename= "";
Private vector file = new vector (); A collection of file names used to save send attachments


/**
* Set 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 display name
*/
public void Setdisplayname (String displayName) {
This.displayname=displayname;
}

/**
* Set whether the server requires identity authentication
*/
public void Setifauth (Boolean Ifauth) {
This.ifauth=ifauth;
}

/**
* Set e-mail user name
*/
public void Setusername (String username) {
This.username=username;
}

/**
* Set e-mail password
*/
public void SetPassword (String password) {
This.password=password;
}

/**
* Set Receiver
*/
public void Setto (String to) {
This.to=to;
}

/**
* Set 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 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 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 mail
*/
Public HashMap Send () {
HashMap map=new HashMap ();
Map.put ("state", "success");
String message= "message sent successfully!" ";
Session Session=null;
Properties props = System.getproperties ();
Props.put ("Mail.smtp.host", smtpserver);
if (Ifauth) {//server requires identity authentication
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 {
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 ()) {//have attachments
Enumeration efile=file.elements ();
while (Efile.hasmoreelements ()) {
Mbp=new MimeBodyPart ();
Filename=efile.nextelement (). toString (); Select each attachment name
Filedatasource fds=new filedatasource (filename); Get the data source
Mbp.setdatahandler (New DataHandler (FDS)); Get the attachment itself and into the bodypart
Mbp.setfilename (Fds.getname ()); Get file name same to enter BodyPart
Mp.addbodypart (MBP);
}
File.removeallelements ();
}
Msg.setcontent (MP); Multipart joined the letter
Msg.setsentdate (New Date ()); Set the date the letter header was sent
Send a letter
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= "message sent failed! Error reason: \ n "+" Authentication Error! ";
E.printstacktrace ();
}catch (Messagingexception e) {
Message= "message sent 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 information:" +message);
Map.put ("message", message);
return map;
}

}

Smtpauth.java Code

The code is as follows Copy 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 messages sent to 163 are all signed with an attachment, whether or not the attachment is sent

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.