Need to send emails in java
Can someone forward me or direct me to the API or documentation that will allow this
thanx
http://www.google.co.uk/search?hl=en&q=java+mail+api&btnG=Google+Search&meta=
Similar Messages
-
Are socket needed to send emails?????
hi guys,
lets say i need to send an email notification everytime i finish doing a cetain task....do i need to create and use a socket to send these emails????
thanks in advance for any help...
lost and blur.
Below are the codes to send email:
(So are socket needed???)
public void execute(String mailto, String mailcc, String mailsub, String mailbody){
//session object inside the catch block also(in case of DCOException).
DCOSession ds = null;
try{
ds = new DCOSession(); // Create new DCOSession object
ds.login("erstest02"); // Log in as current Notes client user
DCOMail dm = new DCOMail(); // Create new DCOMail object
dm.setDcoSession(ds);// Pass DCOSession to mail
//dm.setDebug(true);
dm.setSendTo(mailto);
dm.setCopyTo(mailcc);
//dm.setBlindCopyTo();
dm.setSubject(mailsub);
dm.setBody(mailbody);
//System.out.println("before mail sent");
dm.send(); // Send the mail
ds.logout(); // Log out of the session
System.out.println("mail sent to "+mailto);
}catch(DCOException e1){
e1.printStackTrace();
try{
if(ds!=null){
ds.logout(); //Log out of session even if exception is thrown
}catch(Exception ee1){
System.out.println("Exception thrown while trying to logout of session");
ee1.printStackTrace();
}catch(Exception e){
e.printStackTrace();
try{
if(ds!=null){
ds.logout(); //Log out of session even if exception is thrown
}catch(Exception ee2){
System.out.println("Exception thrown while trying to logout of session");
ee2.printStackTrace();
}lets say i need to send an email notification
everytime i finish doing a cetain task....do i need
to create and use a socket to send these emails????Yes, sockets are needed to send emails. However, you don't need to deal with them yourself. You can use the JavaMail API. It will hide those low level details from you and let you deal with concepts that are related to sending emails--addresses, contents, servers, etc.
http://java.sun.com/developer/onlineTraining/JavaMail/ -
I'm trying to find out how to send emails with java - without using the java mail api - i've been told there is a way to do it but i cant seem to find it - any help on this would be gratefully recieved as i'm totally stuck! :(
Ok, I expanded on it a little bit. Still probably isnt totally correct.
String localhost="yourdomain.com";
String sendMailHost=�mail.domain.com�;
int portNo=25;
String from="[email protected]";
String to="[email protected]";
String message=�Message Body.�;
Socket s = new Socket(SendMailHost,portNo);
DataInputStream in = new DataInputStream(s.getInputStream() ) ;
PrintStream out = new PrintStream(s.getOutputStream() ) ;
out.println("HELO " + locahost);
out.flush() ;
in.readLine(); //ignore response
out.println("MAIL FROM: " + from);
out.flush() ;
in.readLine(); //ignore response
out.println("RCPT TO: " + to);
out.flush() ;
in.readLine(); //ignore response
out.println("DATA");
out.println(message);
out.println(�.�);
s.close(); -
How to send emails using java code
Hi,
can any give me some sample code for sending emails using java languageJavaMail quick start
jGuru: Fundamentals of the JavaMail API -
Need to send email with content of total sales
Hi experts,
I have configure notification mailer and have received also test email. Usually I may receive oracle alerts in my email address.
I need two solutions or need to build below mention point.
1) need to send email total daily sale ?
2) need to setup oracle alerts ?
I am waiting your kind response or refer solid documents to fulfil my requirements
ThanksYou can configure an alert that fires every day at about 1:00 am.
The alert can query oe_order_lines_all table for all orders lines that were created in booked status on the prior day.
Then you can format the alert to include the total amount.
You can group by sales person or by warehouse.
If you want to group the sales by item numbers, the email may become long depending on the number of items you sell every day.
See http://docs.oracle.com/cd/A60725_05/html/comnls/us/alr/summary.htm for a great example on how to send a summary alert.
Hope this helps,
Sandeep Gandhi -
What do i need to know to send email using Java???
hi there
what do i need to know to build an application that sends email? thank you.It would also help if you knew something about how Internet e-mail works. Such as what an SMTP server does, what relaying is and why it's bad, and so on.
-
I am using the following code to send an email from my java servlet but the problem is, when it is on its own it works fine but as soon as I combine it with some code to submit data into a postgres database it sometimes does not perform could it be because im missing some close statements??
//grades to submit grades starts here
String [] paramValues = req.getParameterValues("Mark");
for(int i=0; i<paramValues.length;i++)
String [] paramValues2 = req.getParameterValues("StudentExamNumber");
String Mark = paramValues;
String ExamNo = paramValues2[i];
//testing purposes
out.println("<tr><td>"+ExamNo+"</td>");
out.println("<td>"+Mark+"</td>");
try
st = conn.createStatement();
query = "SELECT StudentNo FROM STUDENTS"+WebCourse2+ " where ExamNo='"+ExamNo+"'";
rs = st.executeQuery(query);
if(rs !=null)
while(rs.next())
String StudentNo=rs.getString("StudentNo");
//testing purposes
//out.println("<td>"+StudentNo+"</td></tr>");
here
st4 = conn.createStatement();
query4 = "select MAX(entryno) from STUDENTRESULTSFORCOURSE"+WebCourse2+" WHERE STUDENTNO='"+StudentNo+"'";
rs4 = st4.executeQuery(query4);
if(rs4 !=null)
while(rs4.next())
EntryNo = rs4.getInt(1);
}//end rs4 while
rs4.close();
}//end rs4 if
out.println("<tr><td>EntryNo= "+EntryNo+"</td>");
EntryNo = EntryNo + 1;
out.println("<td>NewEntryNo= "+EntryNo+"</td></tr>");
//Submitting grades to database/
st3 = conn.createStatement();
insert = "insert into STUDENTRESULTSFORCOURSE"+WebCourse2+" (StudentNo, CourseCode, AttemptNo, ExamMark, EntryNo, EnteredBy) values ('"+StudentNo+"', '"+WebCourse2+"', 1,'"+Mark+"',"+EntryNo+",'"+WebUsername2+"')";
st3.executeUpdate(insert);
}//end rs while
rs.close();
}//end rs if
}//end try
catch (SQLException e)
System.out.println("Error: "+e.getMessage());
}//end for loop
//code to submit grades ends here
//code used to send email starts here
String m_sHostName="localhost";
int m_iPort=25;
try
// Open port to server
smtpSocket = new Socket(m_sHostName, m_iPort);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
if(smtpSocket != null && os != null && is != null)
// Connection was made. Socket is ready for use.
System.out.println("Connection was made. Socket is ready for use.");
try
// The email address that the server
// you are using know user as.
os.writeBytes("MAIL From: <[email protected]>\r\n");
// Who the email is going to.
os.writeBytes("RCPT To: <[email protected]>\r\n");
//send a CC to:
os.writeBytes("RCPT Cc: <[email protected]>\r\n");
// add the message and the
// header of the email to be sent out.
os.writeBytes("DATA\r\n");
os.writeBytes("X-Mailer: Via Java\r\n");
os.writeBytes("From: "+WebUsername2+"<[email protected]>\r\n");
os.writeBytes("To: Marie <[email protected]>\r\n");
//Again if you want to send a CC then add this.
os.writeBytes("Cc: ProfCuthbert <[email protected]>\r\n");
String sMessage = "ELECTRONIC ENGINEERING EXAM COLLATION SYSTEM EMAIL\n\nThe results for the following course have been submitted by the following member of staff\n\nCOURSE: "+WebCourse2+"\n\nSUBMITTED BY: "+WebUsername2+" \n\nPLEASE LOCK COURSE NOW IN ORDER TO PREVENT ANY FURTHER SUBMISSIONS TO BE MADE BY USERS.";
os.writeBytes("Subject: A SUBMISSION HAS BEEN MADE FOR COURSE "+WebCourse2+"\r\n");
os.writeBytes(sMessage + "\r\n");
os.writeBytes("\r\n.\r\n");
os.writeBytes("QUIT\r\n");
// Now send the email off and check the server reply.
// Once an OK is reached you are complete.
String responseline;
//for testing purposes
//out.println(responseline = is.readLine());
while((responseline = is.readLine())!=null)
//for testing purposes
//out.println("responseline= "+responseline+"<br>");
//out.println("responseline.indexOf(Ok)= "+responseline.indexOf("Ok"));
if(responseline.indexOf("Ok") != -1)
break;
if(responseline.indexOf("Ok") == -1)
confirm=1;
if (confirm==1)
out.println("<br>the marks have been submitted thank you");
catch(Exception e)
{ System.out.println("Cannot send email as an error occurred.");
out.println("Cannot send email as an error occurred.");
catch(Exception e)
{ System.out.println("Host " + m_sHostName + "unknown"); }
Does anyone know what the problem is??
thanks
tzafi close them later in the program. Ive made sure they are all closed I have a feeling that it could be coming from here....
//code used to send email starts here
String m_sHostName="localhost";
int m_iPort=25;
try
// Open port to server
smtpSocket = new Socket(m_sHostName, m_iPort);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
if(smtpSocket != null && os != null && is != null)
// Connection was made. Socket is ready for use.
System.out.println("Connection was made. Socket is ready for use.");
try
// The email address that the server
// you are using know user as.
os.writeBytes("MAIL From: <email address>\r\n");
// Who the email is going to.
os.writeBytes("RCPT To: <email address>\r\n");
//send a CC to:
os.writeBytes("RCPT Cc: <email address>\r\n");
// add the message and the
// header of the email to be sent out.
os.writeBytes("DATA\r\n");
os.writeBytes("X-Mailer: Via Java\r\n");
os.writeBytes("From: "+WebUsername2+"<email address>\r\n");
os.writeBytes("To: hello<email address>\r\n");
//Again if you want to send a CC then add this.
os.writeBytes("Cc: hello <email address>\r\n");
String sMessage = "ELECTRONIC ENGINEERING EXAM COLLATION SYSTEM EMAIL\n\nThe results for the following course have been submitted by the following member of staff\n\nCOURSE: "+WebCourse2+"\n\nSUBMITTED BY: "+WebUsername2+" \n\nPLEASE LOCK COURSE NOW IN ORDER TO PREVENT ANY FURTHER SUBMISSIONS TO BE MADE BY USERS.";
os.writeBytes("Subject: A SUBMISSION HAS BEEN MADE FOR COURSE "+WebCourse2+"\r\n");
os.writeBytes(sMessage + "\r\n");
os.writeBytes("\r\n.\r\n");
os.writeBytes("QUIT\r\n");
// Now send the email off and check the server reply.
// Once an OK is reached you are complete.
String responseline;
//for testing purposes
//out.println(responseline = is.readLine());
while((responseline = is.readLine())!=null)
//for testing purposes
//out.println("responseline= "+responseline+"<br>");
//out.println("responseline.indexOf(Ok)= "+responseline.indexOf("Ok"));
if(responseline.indexOf("Ok") != -1)
break;
if(responseline.indexOf("Ok") == -1)
confirm=1;
if (confirm==1)
out.println("<br>the marks have been submitted thank you");
catch(Exception e)
{ System.out.println("Cannot send email as an error occurred.");
out.println("Cannot send email as an error occurred.");
catch(Exception e)
{ System.out.println("Host " + m_sHostName + "unknown"); }
//code used to send email ends here
do i need to close is and os?
thanks
tzaf -
Im using this code to do this, but i have a feeling that I need to close os and is is that the case? do i need to close anything else?
thanks
tzaf
//code used to send email starts here
String m_sHostName="localhost";
int m_iPort=25;
try
// Open port to server
smtpSocket = new Socket(m_sHostName, m_iPort);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
if(smtpSocket != null && os != null && is != null)
// Connection was made. Socket is ready for use.
System.out.println("Connection was made. Socket is ready for use.");
try
// The email address that the server
// you are using know user as.
os.writeBytes("MAIL From: <[email protected]>\r\n");
// Who the email is going to.
os.writeBytes("RCPT To: <[email protected]>\r\n");
//send a CC to:
os.writeBytes("RCPT Cc: <[email protected]>\r\n");
// add the message and the
// header of the email to be sent out.
os.writeBytes("DATA\r\n");
os.writeBytes("X-Mailer: Via Java\r\n");
os.writeBytes("From: "+WebUsername2+"<[email protected]>\r\n");
os.writeBytes("To: Marie <[email protected]>\r\n");
//Again if you want to send a CC then add this.
os.writeBytes("Cc: ProfCuthbert <[email protected]>\r\n");
String sMessage = "ELECTRONIC ENGINEERING EXAM COLLATION SYSTEM EMAIL\n\nThe results for the following course have been submitted by the following member of staff\n\nCOURSE: "+WebCourse2+"\n\nSUBMITTED BY: "+WebUsername2+" \n\nPLEASE LOCK COURSE NOW IN ORDER TO PREVENT ANY FURTHER SUBMISSIONS TO BE MADE BY USERS.";
os.writeBytes("Subject: A SUBMISSION HAS BEEN MADE FOR COURSE "+WebCourse2+"\r\n");
os.writeBytes(sMessage + "\r\n");
os.writeBytes("\r\n.\r\n");
os.writeBytes("QUIT\r\n");
// Now send the email off and check the server reply.
// Once an OK is reached you are complete.
String responseline;
//for testing purposes
//out.println(responseline = is.readLine());
while((responseline = is.readLine())!=null)
//for testing purposes
//out.println("responseline= "+responseline+"<br>");
//out.println("responseline.indexOf(Ok)= "+responseline.indexOf("Ok"));
if(responseline.indexOf("Ok") != -1)
break;
if(responseline.indexOf("Ok") == -1)
confirm=1;
if (confirm==1)
out.println("<br>the marks have been submitted thank you");
catch(Exception e)
{ System.out.println("Cannot send email as an error occurred.");
out.println("Cannot send email as an error occurred.");
catch(Exception e)
{ System.out.println("Host " + m_sHostName + "unknown"); }
//code used to send email ends hereany thoughts?
thanks
tzaf -
Problem: Error while sending Email.(Java Mail API)
Hi to ALL
I am trying to build Application to send Email
Below code is primary code to send Email to other smtp host.
& also debug information is as shown below.
If possible, then please send the solution.
-------------------------------Code :-----------------------------------------
URLName urlN=new URLName("smtps://"+userNm+":"+passwd+"@"+host);
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address= InternetAddress.parse(to, false);
msg.setRecipients(MimeMessage.RecipientType.TO, address);
msg.setSubject("subject");
msg.setContent("messageSend Hi", "text/plain");
Transport transport=session.getTransport(urlN);
transport.connect();
transport.sendMessage(msg, address);
---------- Java Run ----------
DEBUG: setDebug: JavaMail version 1.3.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "hostName", port 465, isSSL true
220 smtp110.mail.mud.yahoo.com ESMTP
DEBUG SMTP: connected to host "hostName", port: 465
EHLO patil
250-smtp110.mail.mud.yahoo.com
250-AUTH LOGIN PLAIN XYMCOOKIE
250-PIPELINING
250 8BITMIME
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XYMCOOKIE"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: use8bit false
MAIL FROM:<from email address>
530 authentication required - for help go to http://help.yahoo.com/help/us/mail/pop/pop-11.html
com.sun.mail.smtp.SMTPSendFailedException: 530 authentication required - for help go to http://help.yahoo.com/help/us/mail/pop/pop-11.html
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1275)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:895)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:524)
at SendEmail2.<init>(SendEmail2.java:46)
at SendEmail2.main(SendEmail2.java:23)
Exception : com.sun.mail.smtp.SMTPSendFailedException: 530 authentication required - for help go to
http://help.yahoo.com/help/us/mail/pop/pop-11.htmls
-------------------------------------------------------------------------------------It's possible. It's only software, after all.
But it's not easy. It effectively involves
screen scraping the HTML pages.
There used to be a third party JavaMail provider
that did all the hard work, but it has disappeared. -
I am not able to send email using JAVA API to outer email
If I am trying to send email from my company account to yahoo I am getting following errors:
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay
for [email protected]
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1196)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at MailSend.main(MailSend.java:116)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to rel
ay for [email protected]
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1047)
... 4 more
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for mkba
[email protected]
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1047)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:584)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at MailSend.main(MailSend.java:116)
Please let me know the reason for the same.Unable to relay - This happened because your Company network don't permit relay. Do talk to the network administrator and check with way safe you can send.
I got the same problem, now im using through gmail. -
Can I send email using Java from my localhost(Tomcat) with Internet connect
Hi friends,
Please tell me can I send email from my localhost (Tomcat) using Java when my computer is connected to Internet?
I don't have any SMTP username or password or the like, as I found in some codes available in net.
Please suggest and any simple code if possible.
Please don't send me the link of JavaMail API to read.
---SujoyThank you for the link. Though I have not tested the provided code, I will test it.
--Sujoy -
Need to send email to email addresses in one list when list 2 is updated
I have 2 lists
list 1 has email addresses
the 2nd list is actually a document library
what I was wondering, is how can I send an email to people to people in list 1 when list #2 is updated with new documents?
i have been trying different ways of doing it, but no luck....
anyone have any ideas how to capture the email address from list 1 and send them an email when list #2 is updated?
seems straight forward but cant find the logic...Hi,
I would suggest you to go for custom event receiver using visual studio. Its an easy way.... try it out.
Choose List item event in event receiver settings.
Step 1:Add item was added and item was updated event. Use caml query to fetch email address and loop through the collection and send email using SPUtility. Refer below code.
/// <summary>
/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
//base.ItemAdded(properties);
using (SPWeb web = properties.OpenWeb())
SPQuery query = new SPQuery();
query.Query = "<OrderBy><FieldRef Name='Title' Ascending='False' /></OrderBy>";
SPList emailList = web.Lists["List1"];//The list which has the email addresses
SPListItemCollection listItemCollection = emailList.GetItems(query);
foreach (SPListItem item in listItemCollection)
SPUtility.SendEmail(web, true, false, item["emailAddress"].ToString(), "Your Mail subject", "Your mail body");
/// <summary>
/// An item was updated.
/// </summary>
public override void ItemUpdated(SPItemEventProperties properties)
//base.ItemUpdated(properties);
//you can provide same code here..if needed.
Step 2: Provide the list2(document library) path as the ListUrl in Element.xml
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Receivers ListUrl="/list2/"> <!--provide document library path...-->
<Receiver>
<Name>EventReceiver1ItemAdded</Name>
<Type>ItemAdded</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>SharePointProject1.EventReceiver1.EventReceiver1</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
<Receiver>
<Name>EventReceiver1ItemUpdated</Name>
<Type>ItemUpdated</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>SharePointProject1.EventReceiver1.EventReceiver1</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
</Receivers>
</Elements>
Deploy it to your SharePoint farm..make sure the feature is activated..and enjoy..
Probably this should work..Check it out and let me know..
Regards,
Dinesh -
Code to Use a button to send email in Java using NetBeans 4.1
I am trying to use a JButton in Java to send an email to another recipient. I am relatively new to Java. Could someone send me the code?
[url http://www.javacommerce.com/displaypage.jsp?name=javamail.sql&id=18274]Sending email from your java applications for idiots who do not know how to search
-
How do I send email from Java?
Is there a class in Java to send email? Is there a third party class to do this? I don't really want to have to implement my own class which connects to the mail server...
If you want a class to send mail...
Here's the code :
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class Mail
// Attributs
public String host = null;
public String to = null;
public String from = null;
public String subject = null;
public String messageText = null;
public String protocol = null;
public Mail()
host = "<your host>";
public void sendMail()
String msgRetour = null;
Properties props = System.getProperties();
props.put( "mail.smtp.host", host );
Session sessionMail = Session.getDefaultInstance( props, null );
try
Message msg = new MimeMessage( sessionMail );
msg.setFrom( new InternetAddress( from ) );
InternetAddress address[] = { new InternetAddress( to ) };
msg.setRecipients( Message.RecipientType.TO, address );
msg.setSubject( subject );
msg.setSentDate( new Date() );
msg.setText( messageText );
Thread mailThread = new TransportThread(msg);
mailThread.start();
catch( MessagingException e )
class TransportThread extends Thread
public Message msgMail;
public TransportThread(Message msg)
msgMail = msg;
public void run()
send();
public void send()
try
Transport.send(msgMail);
catch( MessagingException e ) -
May i know how to send the email by using java?
heres my final i did for java 1 last year (it was a simple email sending program:
//java FINAL!
import javax.swing.*;
import java.net.URL;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class EmailProg extends JPanel implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String composemail = "compose";
static final private String sendmail = "send";
static final private String about = "about";
static final private String submit = "submit";
static final private String exit = "exit";
JLabel lSubmit = new JLabel("Submit");
JButton subbutton = new JButton();
JTextArea emailfrom = new JTextArea(1,1);
JTextArea emailto = new JTextArea(1, 1);
JTextArea emailsubject = new JTextArea(1, 1);
JTextArea emailmessage = new JTextArea(25, 1);
//------BAG LAYOUT
JLabel lFrom = new JLabel("From:");
JTextField cFrom = new JTextField(32);
JLabel lTo = new JLabel("To:");
JTextField cTo = new JTextField(32);
JFrame frame2 = new JFrame("Compose New");
JLabel lSubject = new JLabel("Subject");
JTextField cSubject = new JTextField(32);
JLabel lMessage = new JLabel("Body");
JTextArea cMessage = new JTextArea(5,32);
//====================================
public EmailProg() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar();
addButtons(toolBar);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
textArea.setText("Welcome to Jeff's email program! With this program you can compose and send emails. I hope I get a good grade on thise, and marine world finds a good use for it :-D:-D (implements really just testing the scroller!!!)");
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 110));
add(toolBar, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
//==================================
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("/toolbarButtonGraphics/general/ComposeMail24.gif", composemail ,"Compose new Email", "compose new");
toolBar.add(button);
//second button
button = makeNavigationButton("toolbarButtonGraphics/general/SendMail24.gif", sendmail,"Send The Mail","send");
toolBar.add(button);
//third button
button = makeNavigationButton("toolbarButtonGraphics/general/About24.gif", about,"About","About");
toolBar.add(button);
//exit button
button = makeNavigationButton("toolbarButtonGraphics/general/Stop24.gif", exit, "Exit", "Exit");
toolBar.add(button);
//===================================
protected JButton makeNavigationButton(String imageName, String actionCommand, String toolTipText, String altText) {
//Look for the image.
String imgLocation = imageName;
URL imageURL = EmailProg.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: "+ imgLocation);
return button;
//=============================
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (exit.equals(cmd)){
textArea.setText("");
description = "EXITING";
System.exit(0);
if (composemail.equals(cmd)) { //first button clicked
textArea.setText("");
description = "Write new mail.";
composeWindow();
} else if (sendmail.equals(cmd)) { // second button clicked
textArea.setText("");
description = "This button does'nt do anything yet :x";
} else if (about.equals(cmd)) { // third button clicked
textArea.setText("");
description = "About this program. (See pop-up)";
coolWindow();
else if (submit.equals(cmd))
if (cFrom.getText().equals("")||cTo.getText().equals("")||cSubject.getText().equals("")||cMessage.getText().equals(""))
textArea.setText("One or more of the fields was not filled in.");
else{
try {
String smtpServer="serverhere";
String to=cTo.getText();
String from=cFrom.getText();
String subject=cSubject.getText();
String body=cMessage.getText();
send(smtpServer, to, from, subject, body);
textArea.setText("");
description = "Mail Sent.";
JOptionPane.showMessageDialog(null, "Message Sent.");
catch (Exception ex)
System.out.println("Usage: java com.lotontech.mail.SimpleSender"
+" smtpServer toAddress fromAddress subjectText bodyText");
//CLOSE THE FRAME2 WINDOW IIIIIIIIFFFFFFF SENDING IS SUCCESSFUL!!
}//end of else during send
}//end of if of submit
displayResult(description);
//============================
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
//=============================
public void coolWindow() {
JFrame frame = new JFrame("About");
JTextArea filecontents = new JTextArea();
filecontents.setText("Use the tool bar to compose\n compose new emails, in which you can\n send to anyone on the\n srvhs email server. \n Fill in all the blanks before pressing send. If you dont\n you will receive an error! \n For more information about this program click on the\n information button.");
frame.getContentPane().add(filecontents, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setSize(300,200);
frame.setVisible(true);
//===============================
public void composeWindow() {
frame2.getContentPane().setLayout(new GridBagLayout());
frame2.setResizable(false);
frame2.setSize(600,500);
frame2.setVisible(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 10, 5, 10);
cMessage.setLineWrap(true);
subbutton = makeNavigationButton("toolbarButtonGraphics/general/SendMail24.gif", submit,"submit","submit");
addRow(gbc, lFrom, cFrom);
addRow(gbc, lTo, cTo);
addRow(gbc, lSubject, cSubject);
addRow(gbc, lMessage, cMessage);
addRow(gbc, lSubmit, subbutton);
//===============================
private void addRow(GridBagConstraints gbc, Component left, Component right) {
gbc.gridx = GridBagConstraints.RELATIVE;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.EAST;
frame2.getContentPane().add(left, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
frame2.getContentPane().add(right, gbc);
frame2.pack();
//=======================
public static void send(String smtpServer, String to, String from, String subject, String body) {
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
// -- We could include CC recipients too --
// if (cc != null)
// msg.setRecipients(Message.RecipientType.CC
// ,InternetAddress.parse(cc, false));
// -- Set the subject and body text --
msg.setSubject(subject);
msg.setText(body);
// -- Set some other header information --
msg.setHeader("X-Mailer", "LOTONtechEmail");
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
System.out.println("Message sent OK.");
catch (Exception ex)
ex.printStackTrace();
public static void main(String[] args) {
JFrame frame = new JFrame("EmailProg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EmailProg newContentPane = new EmailProg();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
Maybe you are looking for
-
Satellite P70-A-11V - does HDD protection work without accelerometer?
Hi all, I am new here. I already made another post. In brief, I am pretty much expert in Toshiba Satellite laptops, but my new one, Satellite P70-A-11V, a high-end professional laptop, had some issues. It came with Windows 8, which I upgraded to 8.1.
-
Can itunes remember a podcast's password?
I remember that iTunes used to have a feature that would remember a password for password-protected podcasts. This feature hasn't worked for a while now, and I was wondering if there was a workaround. It just gets annoying having to type this stuff o
-
How to activate HP TrueVision HD webcam
The webcame is not working in my computer. Please suggest how to activate my webcam. Thank you
-
Globus 3 - Oracle as opposed to Postgress
Does anyone have any experience of using Oracle with Globus 3?
-
1920x1080 Full HD vs 1440x1080 Anamorphic
This has got to be one of the most ******** questions ever, but Im asking anyways. What are the pros and cons of 1920 & 1440?? Which one is better? Is 1440 FAKE widescreen?? Why cant Final Cut Express take in full 1920 video, without having to render