I am working with liferay 6.0.6. I am using gmail smtp server to send emails from liferay .In my mail configuration while configuring gmail smtp mail serverI used my gmail id(krishna#gmail.com) . My method has following code .
InternetAddress fromAddress = new InternetAddress("admin#krishnaorg.com");
InternetAddress toAddress = new InternetAddress(emailIdsArray);
MailMessage mailMessage = new MailMessage( fromAddress,toAddress , subject ,mailBody , true);
MailServiceUtil.sendEmail(mailMessage);
When i send a mail. The mail have from address "krishna#gmail.com", but I want from address to be " admin#krishnaorg.com ". How can I achieve this??
This is a full example:
import javax.mail.internet.InternetAddress
import com.liferay.portal.kernel.mail.MailMessage
import com.liferay.mail.service.MailServiceUtil
sender = new InternetAddress()
sender.setAddress("sender#notifier.it")
sender.setPersonal("Sender name")
receiver = new InternetAddress()
receiver.setAddress("cuuvwksw#sharklasers.com")
subject = "mail subject"
body = "body"
message = new MailMessage()
message.setFrom(sender)
message.setTo(receiver)
message.setSubject(subject)
message.setBody(body)
message.setHTMLFormat(false)
MailServiceUtil.sendEmail(message)
try this
mailMessage.setFrom(new InternetAddress("test#liferay.com","your name"));
I got solution for this .
Use following code and try it may work
com.liferay.util.mail.MailEngine.send(InternetAddress from, InternetAddress to, String subject,String body, boolean htmlFormat);
if its bulk mail sending then use following method
com.liferay.util.mail.MailEngine.send(InternetAddress from, InternetAddress[] to, InternetAddress[] cc,String subject, String body, boolean htmlFormat);
InternetAddress[] cc for you can pass null if you don't have cc addresses
Related
I want to program a "Contact Us" form in my desktop application (Swing in Netbeans), just like what we find in some websites.
The problem that I faced is the smtp server name. Actually, I want that the user could send me a message without giving his address mail and without requiring that he connects to his account either.
Here a screen shot:
And this is my Submit button action:
#Override
public void actionPerformed(ActionEvent e) {
boolean isSent = true;
try {
//Properties properties = new Properties();
Properties properties = System.getProperties();
// properties.setProperty("mail.smtp.submitter", contactUs.getMailField().getText());
//properties.setProperty("mail.smtp.auth", "false");
properties.setProperty("mail.smtp.host", "localhost");
//properties.put("mail.smtp.user", txtfrom.getText());
//properties.put("mail.smtp.port", txtPort.getText());
//properties.put("mail.smtp.socketFactory.port", txtPort.getText());
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
//Authenticator mailAuthenticator = new MailAuthenticator();
Session mailSession = Session.getDefaultInstance(properties);
Message message = new MimeMessage(mailSession);
InternetAddress fromAddress = new InternetAddress(contactUs.getMailField().getText());
InternetAddress toAddress = new InternetAddress("mancha#gmail.com");
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(contactUs.getSubjectField().getText());
message.setText(contactUs.getMsgField().getText());
Transport.send(message);
} catch (Exception ex) {
contactUs.getErrorMsg().setText("ERROR:" + ex.getMessage());
isSent = false;
}
if (isSent == true) {
contactUs.getSubmitBtn().setEnabled(false);
contactUs.getErrorMsg().setText("Your e-mail has been sent.");
}
}
Of course I google and I found that simple example which causes always problem of connection to smtp server.
First of all, make sure that your smtp server listens on port 25.
you can check it via telnet.
telnet localhost 25
if you do not have any, install a smtp service to your system.
if you have, check your smtp services security settings to connect it
Firstly check that your mail server is up and running by running
telnet localhost 25
Secondly you don't want to set the fromAddress as the users 'prescribed' email as that would require the account exists on your local mail server (As often people contacting you wouldn't already be on your system). Instead, temporarily hard code the fromAddress to an email address you know exists on your mail server and just append the users email address to the email.
An example of what you might want to do
final String FROM_EMAIL_ADDRESS = yourexistingemail#mailserver.com;
InternetAddress fromAddress = new InternetAddress(FROM_EMAIL_ADDRESS);
message.setText(contactUs.getMsgField().getText(), "\nFrom: " + contactUs.getMailField().getText());
I have used java mail API for sending mail in my application using java and web driver.My requirement is to send a mail whenever a link/url is down.Even though mail is send when i give url incorrectly ,but at the same time if a url is not loading due any other issue (page not found), found that mail is not getting send.
public void SendMail(String url,String str)
{
try
{
Sheet mailsheet = w.getSheet("mail");
String from = mailsheet.getCell(0,1).getContents().toString().trim();
String toEmailID=mailsheet.getCell(1,1).getContents().toString().trim();
Properties props = new Properties();
String mailprotocol = mailsheet.getCell(2,1).getContents().toString().trim();
String mailprotocoltype = mailsheet.getCell(3,1).getContents().toString().trim();
String mailhost = mailsheet.getCell(4,1).getContents().toString().trim();
String mailhostip = mailsheet.getCell(5,1).getContents().toString().trim();
String mailport=mailsheet.getCell(6,1).getContents().toString().trim();
String mailportid=mailsheet.getCell(7,1).getContents().toString().trim();
props.put(mailprotocol,mailprotocoltype);
props.put(mailhost,mailhostip);
props.put(mailport,mailportid);
javax.mail.Session mailSession =javax.mail.Session.getInstance(props);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmailID));
msg.setSubject("Test Summary");
msg.setContent("<html><body>Dear Admin,<br> Website page "+ "<b><i>"+url + "</b></i>"+" cannot be loaded due to the following :<br> <br></body></html>"+str,"text/html");
Transport.send(msg);
System.out.println("Mail is successfully sent to Recipient address with Error information.");
}
catch(Exception e)
{
//System.out.println(e);
System.out.println("Mail cannot be send to Recipient address due to connection error");
}
}
public void x() {
SendMail(url,driver.getTitle());
}
The answer is probably in the bit of code you don't show us : the part where you test the URL.
The response code for a wrong domain name is different from the response code due to a page not found. Also, depending on the system you're targetting, it's possible that page not found are redirected to the index page, making detection even more difficult.
I am using Java mail API to send email through my java application. But I want to send it automatically on future date i.e. any specific date of every month/year. I have used my ISP's SMTP server to send email on mentioned id.I have referred the below available example on net. How to set any specific date here.I have tried SimpleDateFormat and set it here but it still sends mail immediately but set its sent date as mentioned specific date. Is there any other way to send automatic email on mentioned date and time?
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
// Send a simple, single part, text/plain e-mail
public class TestEmail {
public static void main(String[] args) {
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to = "abc#abc.com";
String from = "abc#abc.com";
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = "smtp.yourisp.net";
// Create properties, get Session
Properties props = new Properties();
// If using static Transport.send(),
// need to specify which host to send it to
props.put("mail.smtp.host", host);
// To see what is going on behind the scene
props.put("mail.debug", "true");
Session session = Session.getInstance(props);
try {
// Instantiatee a message
Message msg = new MimeMessage(session);
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test E-Mail through Java");
msg.setSentDate(new Date());
// Set message content
msg.setText("This is a test of sending a " +
"plain text e-mail through Java.\n" +
"Here is line 2.");
//Send the message
Transport.send(msg);
}
catch (MessagingException mex) {
// Prints all nested (chained) exceptions as well
mex.printStackTrace();
}
}
}//End of class
Configure Quartz Job for it. Use cron trigger to specify the execution event
If you're using an EJB 3.0+ container, you could easily use the timer service.
You need to make a session bean, and either implement the TimedObject interface or annotate a method with #Timeout. You can get an instance of the TimerService from the InitialContext via getTimerService(), then create a timer with one of the createTimer() variants. It can take an interval, or a Date object specifying when it expires...
I am looking for a Java class that will allow me to send emails without the need for SMTP. Like the PHP mail() class that uses sendmail.
Any suggestions?
Many Thanks
James
Before Using this Program, you need to have Javasoft's JavaMail class files which can be downloaded from here http://www.javasoft.com/products/javamail/index.html
You will also need the JavaBeansTM Activation Framework extension or JAF (javax.activation). It is available at http://java.sun.com/beans/glasgow/jaf.html.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.jcom.net");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
I found it:
http://examples.oreilly.com/jenut/SendMail.java
Thanks all.
All mail senders will need an SMTP server to transfer their mail. The nice thing about PHP mail is that you don’t need to configure it (it use the sendmail binary directly, if sendmail is not installed, PHP mail will not work either).
If all you want is building a Java application that can send out e-mail without configuring an SMTP server for that, you could use a Java based SMTP server, for example:
Apache James
I need to send simple html-message with JavaMail. And when I tried to find some nice examples with explanations in the Internet, each next example made me more angry and angry.
All those silly examples contain copied and pasted Java code which differs only in comments and a nice disclaimer that first you should config your smtp and pop3 server.
I understand that nobody wants to make an advertise for some concrete products but configuring the server is imho the hardest part. So, can anyone give me some really useful information (without java code) about configuring concrete server (Kerio, for example, or any other one)?
What I have now is the next exception:
250 2.0.0 Reset state
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Relaying to <mymail#mycompany.com> denied (authentication required)
UPD. Simple reformulation of all previous text is: imagine that you have Windows, jdk, and nothing else. And you want to make java program and run it on your machine. And this program should send "Hello world!" to your gmail account. List your steps.
UPD2. Here is the code:
Properties props = new Properties ();
props.setProperty ("mail.transport.protocol", "smtp");
props.setProperty ("mail.host", "smtp.gmail.com");
props.setProperty ("mail.user", "my_real_address_1#gmail.com");
props.setProperty ("mail.password", "password_from_email_above");
Session mailSession = Session.getDefaultInstance (props, null);
mailSession.setDebug (true);
Transport transport = mailSession.getTransport ();
MimeMessage message = new MimeMessage (mailSession);
message.setSubject ("HTML mail with images");
message.setFrom (new InternetAddress ("my_real_address_1#gmail.com"));
message.setContent ("<h1>Hello world</h1>", "text/html");
message.addRecipient (Message.RecipientType.TO,
new InternetAddress ("my_real_address_2#gmail.com"));
transport.connect ();
transport.sendMessage (message,
message.getRecipients (Message.RecipientType.TO));
And exception is:
RSET
250 2.1.5 Flushed 3sm23455365fge.10
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. 3sm23455365fge.10
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886)
at com.teamdev.imgmail.MailSender.main(MailSender.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
...
If you're looking for a tutorial to configure an SMTP server, you shouldn't be looking for JavaMail. Simply look for a tutorial on your server of choice (Kerio, for example ... or Exim, SendMail, Apache James, Postfix) or ask on Serverfault. Any SMTP-compliant server will play nicely with JavaMail.
Alternatively, you may even use any "standard" mail provider's infrastructure. For example, I use a Google Apps account along with Google's SMTP infrastructure to send mail from our Java applications. Using a Gmail account is a good starting point anyway if you don't want to setup your own SMTP server in order to simply testdrive JavaMail.
As a last option, you might even lookup the MX Records for a domain and deliver your mails directly to the SMTP server of the recipient. There are some common gotchas to workaround tough.
As a last point, you'll have to look into how to avoid that your mails be filtered as spam - which is a huge topic itself. Here it helps to rely on standard providers that will deal with some of the issues you might encounter when hosting your own server.
Btw: Regarding the error message you posted: the SMTP server is denying relaying of messages. This is if your SMTP server (thinks that it) is running on example.com and you're sending as bob#example.net to alice#example.org, you're asking the SMTP server to act as a relay. This was common practice several years ago, until it was - you guessed it - abused by spammers. Since those days, postmasters are encouraged to deny relaying. You have two choices: authenticate before sending mail or send to accounts hosted at your server only (i.e. on example.com, e.g. alice#example.com).
Edit:
Here is some code to get you started with authenticationg (works with Gmail accounts but should do for your own server as well)
private Session createSmtpSession() {
final Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "" + 587);
props.setProperty("mail.smtp.starttls.enable", "true");
// props.setProperty("mail.debug", "true");
return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("john.doe#gmail.com", "mypassword");
}
});
}
I can see part of your problem. It's adequately explained in the error message.
The SMTP server you are sending your mail to (i.e. one of the addresses you've configured in your JavaMail configuration) is refusing to forward mail to mymail#company.com. Looks like a configuration issue in your SMTP server. As sfussenegger indicated, it has nothing to do with javamail.
So you're not debugging on all fronts at the same time, it might be a good idea to try addressing your SMTP server from a known working SMTP client. Thunderbird would do fine, for example. If you can send mail through it from Thunderbird, there should be little problem from JavaMail.
Update:
The correct address for Google's SMTP server is: smtp.gmail.com . Is this the server you have configured in JavaMail? Can you show us the matching error message?
A working example combining the above answers, using activation-1.1.jar and mail-1.4.1.jar and the SMTP host is Gmail.
Replace user#gmail.com and user_pw in line return new PasswordAuthentication("user#gmail.com", "user_pw");
Also, you want to replace myRecipientAddress#gmail.com by the email address where you want to receive the email.
package com.test.sendEmail;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class sendEmailTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
sendEmailTest emailer = new sendEmailTest();
//the domains of these email addresses should be valid,
//or the example will fail:
emailer.sendEmail();
}
/**
* Send a single email.
*/
public void sendEmail(){
Session mailSession = createSmtpSession();
mailSession.setDebug (true);
try {
Transport transport = mailSession.getTransport ();
MimeMessage message = new MimeMessage (mailSession);
message.setSubject ("HTML mail with images");
message.setFrom (new InternetAddress ("myJavaEmailSender#gmail.com"));
message.setContent ("<h1>Hello world</h1>", "text/html");
message.addRecipient (Message.RecipientType.TO, new InternetAddress ("myRecipientAddress#gmail.com"));
transport.connect ();
transport.sendMessage (message, message.getRecipients (Message.RecipientType.TO));
}
catch (MessagingException e) {
System.err.println("Cannot Send email");
e.printStackTrace();
}
}
private Session createSmtpSession() {
final Properties props = new Properties();
props.setProperty ("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "" + 587);
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty ("mail.transport.protocol", "smtp");
// props.setProperty("mail.debug", "true");
return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user#gmail.com", "user_pw");
}
});
}
}
This should work:
import java.text.MessageFormat;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Emailer {
public static void main(String[] args) {
String hostname = args[0];
final String userName = args[1];
final String passWord = args[2];
String toEmail = args[3];
String fromEmail = args[4];
String subject = args[5];
String body = "";
// add rest of args as one body text for convenience
for (int i = 6; i < args.length; i++) {
body += args[i] + " ";
}
Properties props = System.getProperties();
props.put("mail.smtp.host", hostname);
Session session = Session.getInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, passWord);
}
});
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(fromEmail));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
} catch (MessagingException e) {
System.out.println("Cannot send email " + e);
}
}
}
You need to put the JavaMail mail.jar on your classpath for the javax.mail dependencies.
I'm not sure if Google lets you send email like you want to. How about trying another email provider, like your ISP's?