How to implement Java mail sending and with attachments

Source: Internet
Author: User
Tags sendfile

How to implement Java mail sending and with attachments
Java Mail sends the same, you can implement the parameters passed by port address, password, name, who sent, to whom, subject, body content, SMTP address, send type
and other functions.
Method One

Simple JavaMail Message Delivery
Dev.firnow.com Time: 2009-04-05 Author: Anonymous Edit: Sky click: 683 [Comments]
-
-

Import javax.mail.*;
Import java.util.*;
Import javax.mail.internet.*;

/**
* @author Caoyx
*
*/
public class MailTest {

/**
* Construction Method
*/
Public MailTest () {

}

/**

*

*javamail Send Test

*/

public void Sendemailtest () {


Properties Props Tutorial = new properties ();
Props.put ("Mail.smtp.host", "smtp.163.com");

Allow SMTP checksum
Props.put ("Mail.smtp.auth", "true");
Session sendmailsession = session.getinstance (props, null);

try {
Transport transport = Sendmailsession.gettransport ("SMTP");

Mailbox Server login Email username login password
Transport.connect ("smtp.163.com", "xxx", "xxx");
Message Newmessage = new MimeMessage (sendmailsession);

Set Mail topics
String Mail_subject = "Mail send test (mail header)";
Newmessage.setsubject (Mail_subject);

Set the sender's address
String strfrom = "xiangzi551@163.com";
Strfrom = new String (Strfrom.getbytes (), "8859_1");
Newmessage.setfrom (New InternetAddress (strfrom));
Address addressfrom[] = {
New InternetAddress ("xiangzi551@163.com"),
New InternetAddress ("Xiangzi551@163.c dfgdom")};

Change Sender Address
Newmessage.addfrom (Addressfrom);

Set recipient Address
Address addressto[] = {new InternetAddress ("cyx_shzu@163.com")};
Newmessage.setrecipients (Message.RecipientType.TO, Addressto);

Set Mail body
Newmessage.setsentdate (New Java.util.Date ());

String Mail_text = "Mail send test. From:" +strfrom;
Newmessage.settext (Mail_text);

Save Send information
Newmessage.savechanges ();

Send mail
Transport.sendmessage (Newmessage, Newmessage
. Getrecipients (Message.RecipientType.TO));

Transport.close ();

System.out.println ("OK");
catch (Exception e) {
System.out.println (e);
}

}

public static void Main (String args[]) throws Exception {
MailTest semail = new MailTest ();
Semail.sendemailtest ();
}

}

Test:

Create a Java application in eclipse

Introduction of Mail.jar Activation.jar

Example Two

Import java.util.Properties;

Import Javax.mail.Authenticator;
Import Javax.mail.Folder;
Import Javax.mail.Message;
Import Javax.mail.Part;
Import javax.mail.PasswordAuthentication;
Import javax.mail.Session;
Import Javax.mail.URLName;
Import javax.mail.internet.InternetAddress;

public class MainClass {

public static void Main (string[] args) throws Exception {
URLName Server = new URLName ("Protocol://username@host/foldername");

Session session = Session.getdefaultinstance (new Properties (), New Mailauthenticator ());

Folder folder = Session.getfolder (server);
if (folder = = null) {
System.out.println ("folder" + server.getfile () + "not found.");
System.exit (1);
}
Folder.open (folder.read_only);

message[] messages = Folder.getmessages ();
for (int i = 0; i < messages.length; i++) {
System.out.println (messages[i].getsize () + "bytes long.");
System.out.println (Messages[i].getlinecount () + "lines.");
String disposition = messages[i].getdisposition ();
if (disposition = = null) {
; Doing nothing
}else if (disposition.equals (Part.inline)) {
System.out.println ("This part should to be displayed inline");
else if (disposition.equals (part.attachment)) {
System.out.println ("This is a attachment");
String fileName = Messages[i].getfilename ();
System.out.println ("The file name of this attachment is" + fileName);
}
String description = Messages[i].getdescription ();
if (description!= null) {
SYSTEM.OUT.PRINTLN ("The description of this" + description);
}
}
Folder.close (FALSE);
}
}

Class Mailauthenticator extends Authenticator {

Public Mailauthenticator () {
}

Public Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication ("username", "password");
}
}

How to use Filedatasource to send a file by mail

Import java.util.*;
Import java.io.*;
Import javax.mail.*;
Import javax.mail.internet.*;
Import javax.activation.*;

public class Sendfile {

public static void Main (string[] args) {
if (args.length!= 5) {
System.out.println ("Usage:java sendfile <to> <from> <smtp> <file> true|false");
System.exit (1);
}

String to = args[0];
String from = args[1];
String host = args[2];
String filename = args[3];
Boolean debug = Boolean.valueof (Args[4]). Booleanvalue ();
String MSGTEXT1 = "Sending a FILE.N";
String subject = "Sending a file";

Create some properties and get the default session
Properties props = System.getproperties ();
Props.put ("Mail.smtp.host", host);

Session session = Session.getinstance (props, null);
Session.setdebug (Debug);

try {
Create a message
MimeMessage msg = new MimeMessage (session);
Msg.setfrom (New InternetAddress (from));
Internetaddress[] Address = {new internetaddress (to)};
Msg.setrecipients (Message.RecipientType.TO, address);
Msg.setsubject (subject);

Create and fill the
MimeBodyPart MBP1 = new MimeBodyPart ();
Mbp1.settext (MSGTEXT1);

Create the second message part
MimeBodyPart MBP2 = new MimeBodyPart ();

Attach the "file to" message
Filedatasource FDS = new Filedatasource (filename);
Mbp2.setdatahandler (New DataHandler (FDS));
Mbp2.setfilename (Fds.getname ());

Create the Multipart and add its parts to it
Multipart MP = new Mimemultipart ();
Mp.addbodypart (MBP1);
Mp.addbodypart (MBP2);

Add the Multipart to the message
Msg.setcontent (MP);

     //Set the Date:header
      msg.setsentdate (New Date ( ));
     
     /Send the message
       transport.send (msg);
     
 } catch (Messagingexception Mex) {
      Mex.printstacktrace ();
      Exception ex = null;
      if ((ex = Mex.getnextexception ())!= null) {
    Ex.printstacktrace ();
     }
 }
   }
}

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.