send email with SMTP command, using socket programming in Java - java

I am trying to send email via socket programming using SMTP commands using socket in java. But i am unable to do so. The problem is in authentication may be.
I need SMTP commands to send email and to authenticate user over server.
Any help appreciated.
Thanks in Advance
Imran

Create Transport Object
Properties props = new Properties();
props.setProperty("mail.transport.protocol", pProtocol);
props.setProperty("mail.host", pHost);
props.setProperty("mail.user", pUser);
props.setProperty("mail.password", pPassword);
mMailSession = Session.getDefaultInstance(props, null);
mMailSession.setDebug(true);
try {
mTransport = mMailSession.getTransport();
mTransport.connect();
} catch (MessagingException e) {
mLog.error(e.getMessage(), e);
throw new MailException(e);
}
Send mail
try {
MimeMessage message = new MimeMessage(mMailSession);
message.setSubject(pSubject);
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(pContent, "text/html");
Multipart mp = new MimeMultipart();
mp.addBodyPart(textPart);
message.setContent(mp);
message.addFrom(new Address[] { new InternetAddress(pFrom) });
for (int i = 0; i < pTo.length; i++) {
String tTo = pTo[i];
message.addRecipient(Message.RecipientType.TO, new InternetAddress(tTo));
}
mTransport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
} catch (MessagingException me) {
throw new MailException(me);
}
EDIT:
After the comment from Thilo, i would like to append, that this solution depend on com.sun.mail and imports javax.mail.* classes.

Related

email sending with multiple attachments using MultipartFile

I am using MultipartFile to send an email with multiple attachments. my code is working fine but I am storing each file in my project then I am attaching. I don't want to store that file anywhere instead I want the file directly send to the recipients.
My code is,
Controller:
#RequestMapping(value="/sendEmailAttachment",method=RequestMethod.POST)
public #ResponseBody Response sendEmail(#RequestParam("file") MultipartFile[] file,#ModelAttribute Email email) {
SendEmail mail = new SendEmail();
return mail.sendEmail(email,file);
}
Service:
public Response sendEmail(Email email,MultipartFile[] attachFiles) {
username = email.getUsername();
password = email.getPassword();
switch (email.getDomain()) {
case "1and1.com":
host = "smtp.1and1.com";
break;
case "gmail.com":
host = "smtp.gmail.com";
break;
case "yahoo.com":
host = "smtp.mail.yahoo.com";
break;
case "rediffmail.com":
host = "smtp.rediffmail.com";
break;
default:
host = "smtp.1and1.com";
username="support#gmail.com";
password="************";
break;
}
props.put("mail.smtp.host", host);
Response response = new Response();
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
InternetAddress[] myToList = InternetAddress.parse(email.getTo());
InternetAddress[] myBccList = InternetAddress.parse(email.getBcc());
InternetAddress[] myCcList = InternetAddress.parse(email.getCc());
// Set From: header field of the header.
message.setFrom(new InternetAddress(email.getUsername()));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,myToList);
message.setRecipients(Message.RecipientType.BCC, myBccList);
message.setRecipients(Message.RecipientType.CC, myCcList);
// Set Subject: header field
message.setSubject(email.getSubject());
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setContent(email.getBody(), "text/html");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
if(attachFiles != null && attachFiles.length > 0){
for (MultipartFile filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
filePath.transferTo(new File(filePath.getOriginalFilename()).getAbsoluteFile());
attachPart.attachFile(filePath.getOriginalFilename());
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// Send the complete message parts
message.setContent(multipart);
// Transport.send(message, message.getAllRecipients());
Transport.send(message);
response.setStatus(200);
response.setMessage("Sent Email Successfully");
} catch (MessagingException e) {
response.setStatus(-1);
response.setMessage(""+e);
response.setObject(e);
e.printStackTrace();
}
return response;
}
Here I have witten like,
filePath.transferTo(new File(filePath.getOriginalFilename()).getAbsoluteFile());
attachPart.attachFile(filePath.getOriginalFilename());
I dont want to transfer/save file into the project and attach, I want to send the file directly. any help will appreciated.
Try this:
attachPart.setContent(filePath.getBytes(), filePath.getContentType());
attachPart.setFileName(filePath.getOriginalFilename());
attachPart.setDisposition(Part.ATTACHMENT);
In my case, the answer of #Bill Shannon give me the error "java.io.IOException: “text/plain” DataContentHandler requires String object, was given object of type class [B"
I modified the code like this :
DataSource ds = new ByteArrayDataSource(filePath.getBytes(), filePath.getContentType());
attachPart.setDataHandler(new DataHandler(ds));
attachPart.setFileName(filePath.getOriginalFilename());
attachPart.setDisposition(Part.ATTACHMENT);
If you are using Spring, then you can use JavaMailSenderImpl and MimeMessageHelper:
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
MimeMessage mailMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true);
helper.addAttachment("fileName", filePath);
mailSender.send(mailMessage);
List<MultipartFile> attachments = /* this will be input for multiple files */
Multipart multipart = new MimeMultipart();
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(/* email content */, "text/html");
multipart.addBodyPart(mimeBodyPart);
for(int i = 0 ; i < attachments.size() ; i++) {
mimeBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(attachments.get(i).getBytes(), attachments.get(i).getContentType());
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(attachments.get(i).getOriginalFilename());
multipart.addBodyPart(mimeBodyPart);
}
email.setContent(multipart);

Javamail adding attachment prevent mail to be sent

I'm struggling with Javamail, I'm trying to send emails with a zip file attached.
When I try to send a mail without attachment, it works fine but when I add the zip the mail is no longer sent. I have no errors...
My code :
LOGGER.info("########################### Send Email with attachement to " + destination + " Start ######################");
//Config smtp mail
Properties props = new Properties();
props.put("mail.smtp.host", getSmtpHost());
props.put("mail.smtp.socketFactory.port", getSmtpsocketFactoryPort());
props.put("mail.smtp.socketFactory.class", getSmtpsocketFactoryClass());
props.put("mail.smtp.auth", getSmtpAuth());
props.put("mail.smtp.port", getSmtpPort());
//instance Session
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getUsername(), getPassword());
}
});
try {
//construction objet mail
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(getFromAddress()));
//Send Email to Addresse
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination));
message.setSubject(objet);
message.setSentDate(new Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(contenu);
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
String fileName = attachementPath + attachementName;
File file = new File (fileName);
attachmentBodyPart.attachFile(file);
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
//send Email
Transport.send(message);
LOGGER.info("########################### Send email with attachement to " + destination + " End ########################### ");
} catch (MessagingException e) {
LOGGER.error("Error when send email to " + destination);
throw new RuntimeException(e);
}
I've tryied a lot of things, I may be to tired to find the mistake xD
Thanks for the help !!
Update : Thanks to jmehrens I've found the issue. My mail server doesn't allow .zip
Make sure your mail server doesn't have a policy in place that prevents the delivery of emails with the extension of .zip. You should be able to test that with just a mail client (or JavaMail) and rename the extension to either .txt or even .piz.
Read the JavaMail FAQ. It is full of good information on best practices, debugging and troubleshooting steps.

Error when sending email via Java Mail API?

I got following error when trying to send email via Java Mail API? What does this error mean?
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2210)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
Here is my code, i set all parameters (from, to , subjects and attachments)
public static void send(MailUtil mailUtil) throws MessagingException {
MimeMessage message = new MimeMessage(session);
if (props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER) != null) {
message.setFrom(new InternetAddress(props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER)));
} else {
message.setFrom(new InternetAddress(mailUtil.getFrom()));
}
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(mailUtil.getTo()));
if (mailUtil.getBcc() != null && mailUtil.getBcc().trim().length() > 0) {
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailUtil.getBcc()));
} else {
message.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(""));
}
message.setSubject(mailUtil.getSubject(), "UTF-8");
// Check for files list and attach them.
if (mailUtil.attachmentFiles != null && mailUtil.attachmentFiles.size() > 0) {
Multipart multipart = new MimeMultipart();
// Set content.
BodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setContent(mailUtil.getContent(), "text/plain; charset=utf-8");
multipart.addBodyPart(messageBodyPart);
// Attach files.
for (File file : mailUtil.attachmentFiles) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
} else {
//message.setContent("<h1>Hello world</h1>", "text/html");
message.setContent(mailUtil.getContent(), "text/html; charset=UTF-8");
}
Transport.send(message);
}
I just think is there any problem with my paramters?
Belows is my configuration
mail.smtp.port=465
mail.smtp.starttls.enable=true
mail.smtp.auth=true
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.timeout=25000
mail.smtp.host=smtp.gmail.com
mail.username = username#gmail.com
mail.password = mypassword
mail.sender = sender#gmail.com
mail.receiver = receiver#gmail.com
mail.subject = mysubject
I am using google mail server! I dont' think there is problem there!
Belows is session initiation
final String userName = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_USERNAME);
final String passWord = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_PASSWORD);
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,
passWord);
}
});
I believe it absolutely relates to server configuration.
When I change the port configuration from 465 to 587, it solves my problem!
Anyway, thank you guy for your help!
Your code and configuration contain many of these common mistakes. In particular, the use of Session.getDefaultInstance may mean you're not using the configuration you think you're using. If fixing that doesn't solve your problem, post the JavaMail session debug output.
I'm not sure why you use a "mail" object to setup the connection properties, instead try this, it should work, I've tested myself:
private Properties props;
props = System.getProperties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
message.setFrom(new InternetAddress("YOUR EMAIL ADDRESS HERE"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECEIVER EMAIL ADDRESS HERE"));
message.setSubject("SUBJECT");
message.setText("THE EMAIL TEXT");
Transport.send(message);
} catch (MessagingException e) {e.printStackTrace();}
}

GAE not working for send mail using Send Grid using java

I'm trying to send a mail using SendGrid by deploying my code to GAE. Following is my code.
private static final String SMTP_HOST_NAME = "smtp.sendgrid.net";
private static final String SMTP_AUTH_USER = "*******";
private static final String SMTP_AUTH_PWD = "*******";
private static final int SMTP_PORT = 2525;
public void sendCustomer(String userName, String toEmail, int custId) {
try {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
Multipart multipart = new MimeMultipart("alternative");
// Sets up the contents of the email message
BodyPart part1 = new MimeBodyPart();
part1.setText("Hello "
+ userName
+ "\n\n\n\n"
+ "Welcome to NotionViz. You have been registered successfully in NotionViz.");
multipart.addBodyPart(part1);
message.setText("UTF-8", "html");
message.setContent(multipart);
message.setFrom(new InternetAddress(SMTP_AUTH_USER));
message.setSubject("Customer Registration");
InternetAddress internetAddress = null;
try {
internetAddress = new InternetAddress(toEmail);
internetAddress.validate();
} catch (Exception e) {
System.out.println("Not a valid email address");
}
message.addRecipient(Message.RecipientType.TO, internetAddress);
InternetAddress address = new InternetAddress("cloud.spaninfotech#gmail.com");
message.setFrom(address);
// Sends the email
transport.connect(SMTP_HOST_NAME, SMTP_PORT, SMTP_AUTH_USER,
SMTP_AUTH_PWD);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.sendMessage(message,
message.getFrom());
transport.close();
} catch (Exception e) {
}
}
// Authenticates to SendGrid
class SMTPAuthenticator extends javax.mail.Authenticator {
#Override
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
This program is working fine and sending mail in local. But if i deploy to GAE and check, I'm not getting an email. Please let me know why GAE restricting third party mail sending.
Try changing the port that you're using. You can hit SendGrid over port 587, 25 or 2525 for plain/TLS connections (465 if you were going to be using SSL).
SendGrid suggests port 587 to avoid rate limits set by some hosting companies so I would give that a shot.
On GAE sockets are a subject to a series of restrictions (see Sockets API documentation). Authenticated SMTP is allowed on submission port 587, so you can use it as already suggested by LaCroixed.

javaMail with Lotus server

im facing some problems with Lotus server.
The guy that is in charge of the server is telling me that the configuration is ok, but i cant send mail with html body with his lotus server.
The error i get is : “554 Relay rejected for policy reasons.”
When i tried on my pc, i used smpt.gmail.com and worked like a champ. So i believe is not a code problem and the issue is with the server configuration.
Is there a problem with javaMail and Lotus? is it a common issue? (in one blog some guy was saying that it can not be possible to send html but i cant believe that)
My code just in case,
public void sendEmail(String toEmailAddr, String subject, String issue) {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress toAddress = null;
InternetAddress toAddress2[] = null;
Transport t = null ;
try {
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(issue, "text/html");
mp.addBodyPart(htmlPart);
simpleMessage.setContent(mp);
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
toAddress = new InternetAddress(toEmailAddr);
toAddress2 = new InternetAddress [1];
toAddress2[0] = toAddress;
} catch (AddressException e) {
// TODO LOG
e.printStackTrace();
}
try {
simpleMessage.setRecipients(RecipientType.TO, toAddress2);
simpleMessage.setSubject(subject);
t = mailSession.getTransport("smtp");
if(userPwd==null)
userPwd = "";
t.connect(host, userName, userPwd);
t.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
} catch (MessagingException e) {
e.printStackTrace();
// TODO LOG
}finally{
try {
t.close();
} catch (MessagingException e) {
// TODO LOG
}
}
}
Regards.
SMTP on the Domino server has most likely been set up to only allow relay by certain hosts - therefore the error message 554 Relay rejected for policy reasons.
You should talk to the admin and have him change the configuration to allow relay by other hosts. This is configured in a configuration document in the Router/SMTP -> Restrictions and Controls -> SMTP Inbound Controls section. More information on SMTP inbound relay controls is available here:
http://publib.boulder.ibm.com/infocenter/domhelp/v8r0/index.jsp?topic=%2Fcom.ibm.help.domino.admin.doc%2FDOC%2FH_SETTING_INBOUND_RELAY_CONTROLS_STEPS.html
i had the same problem and solved it. The FROM part was "me#example.com" and changed it to "myname#mydomain.com" and it began to send
May require Secure Connection(SSL), Use the following properties to connect mail server supporting smtp protocol:
properties.put("mail.smtp.socketFactory.port", "SMTP_PORT");
properties.put("mail.smtp.host", "SMTP_SERVER_HOST_NAME_OR_IP");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");

Categories