SwiftMailer using G Suite Issue - swiftmailer

I am trying to setup SwiftMailer on my server. I am using the example configuration from the SwiftMailer docs for testing. I have a paid G Suite account but haven't finished setting up SSL on the server yet. I am running Cent OS 6.8 and Apache 2.2. I have googled everything I can think of and tried all the proposed solutions with no success.
My script is as follows, obviously my email address and credentials are correct in the real script. I appreciate any advice.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('swiftmailer-5.x/lib/swift_required.php');
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp-relay.gmail.com', 25)
->setUsername('myemail#mydomain.com')
->setPassword('*****')
;
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Swift Mailer Test')
->setFrom(array('my from address'))
->setBody('Here is the message itself')
;
// Send the message
$failedRecipients = array();
$numSent = 0;
$to = array('another#email.com' => 'Joe');
foreach ($to as $address => $name)
{
if (is_int($address)) {
$message->setTo($name);
} else {
$message->setTo(array($address => $name));
}
$numSent += $mailer->send($message, $failedRecipients);
}
printf("Sent %d messages\n", $numSent);
?>
When I run this script I get the following very vague error:
"Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp-relay.gmail.com [Connection timed out #110]' in /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Transport/StreamBuffer.php:269 Stack trace: #0 /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Transport/StreamBuffer.php(62): Swift_Transport_StreamBuffer->_establishSocketConnection() #1 /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Transport/AbstractSmtpTransport.php(113): Swift_Transport_StreamBuffer->initialize(Array) #2 /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Mailer.php(79): Swift_Transport_AbstractSmtpTransport->start() #3 /var/www/html/appreciate-erp/mailtest.php(42): Swift_Mailer->send(Object(Swift_Message), Array) #4 {main} thrown in /var/www/html/appreciate-erp/swiftmailer-5.x/lib/classes/Swift/Transport/StreamBuffer.php on line 269"

As of https://support.google.com/a/answer/176600, it seems like SMTP Relay on G-Suite applies IP address restriction. The "could not connect" error would fit as the result of a missing configuration or the attempt to connect from another IP address as the one configured. Hope this helps!

Related

Fatal error: Uncaught Error: Call to undefined method PHPMailer\PHPMailer\PHPMailer::setForm()

here is my code
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
if(isset($_POST["send"])){
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'random#gmail.com'; // Your gmail
$mail->Password = 'rqbsmgrfefohmokx'; // Your gmail password
$mail->SMTPSecure= 'ssl';
$mail->Port = 465;
$mail->setForm('random#gmail.com'); // Your gmail
$mail->addAdress($_POST["email"]);
$mail->isHTML(true);
$mail->Subject = $_POST["subject"];
$mail->Body = $_POST["message"];
$mail->send();
echo
"
<script>
alert('Sent Succesfully');
document.location.href = 'index.php';
</script>
" ;
}
?>
i got this error
Fatal error: Uncaught Error: Call to undefined method PHPMailer\PHPMailer\PHPMailer::setForm() in C:\xampp\htdocs\sendmail\send.php:20 Stack trace: #0 {main} thrown in C:\xampp\htdocs\sendmail\send.php on line 20 Any ideas???
I really dont know from what this error comes... so i hope someone to help me/guide me
The most important thing to do in situations like this is read the error message. In this case the message is telling you that the setForm method does not exist. This is correct, and if you go and look at any of the PHPMailer examples or drill into the class itself, you’ll realise that the method name you’re looking for is setFrom, with the r and o the other way around.

Laravel echo/pusher not sending ping when receiving data

I'm running a laravel websocket and have a connection over wss.
I am running commands on the server, and the commands are logged in a file. Each line is also sent over a websocket to the front-end so I can view it. Each laravel-command has it's own file and broadcast-channel.
Commandlogger:
class CommandLogger implements Logger {
public $commandname = '';
public $broadcast = false;
public function __construct($commandname, $broadcast = false) {
$this->commandname = Str::camel(Str::slug($commandname));
$this->broadcast = $broadcast;
}
function log($message) {
$message = Carbon::now()->format('Y-m-d H:i:s').": ".$message;
file_put_contents(storage_path("logs/commands/$this->commandname.log"), $message.PHP_EOL , FILE_APPEND | LOCK_EX);
if($this->broadcast) {
event(new CommandLogCreated($message, $this->commandname));
}
}
}
In Vue.js I listen with Echo(which implements pusherjs):
Echo.private('logs.commands.' + command)
.listen('.command-log:created', event => {
this.log[command] += event.message + "\n";
let splitLog = this.log[command].split("\n");
let splitLength = splitLog.length;
if(splitLength > 200) {
splitLog = splitLog.slice(splitLength - 200, splitLength);
}
this.log[command] = splitLog.join('\n');
this.trigger++;
})
.error(error => {
console.log(error);
});
The issue I'm experiencing only happens when the command is sending a lot of messages to echo.
At a normal rate, with some pauses between the messages, echo does the ping-pong and the connection remains receiving messages.
At higher message rates, is seems echo is not sending the ping-pong and my socket silently stops receiving data. After it stops receiving it starts ping-ponging as if nothing happend. No disconnect has occured on both server and client.
Websocket messages(notice it stops at 205000, gives no error and resumes ping-pong):
Actual command output(at 230000 and still running):
If I refresh the page, I will receive messages again.
I've updated the websockers:serve command (vendor/beyondcode/laravel-websockets/src/Console/Commands/StartServer.php) directly and disabled the pongtracker:
protected function configurePongTracker()
{
//$this->loop->addPeriodicTimer(10, function () {
// $this->laravel
// ->make(ChannelManager::class)
// ->removeObsoleteConnections();
//});
}
Then I rebooted the websocket and tried again. This time, no matter how fast I was sending messages in, echo keeps receiving messages.
TL;DR:
My conclusion is that echo should ping-pong in between receiving messages from the server, because currently it seems to fail at doing so, and the websocket cleans the connection eventually without disconnecting. How can I either force echo to do the ping-pong, or make sure the server does not clean the connection without running the risk of having runaway connections?
Update 1:
I've been diving a little more into the Startserver.php file and found this:
public function removeObsoleteConnections(): PromiseInterface
{
if (! $this->lock()->acquire()) {
return Helpers::createFulfilledPromise(false);
}
$this->getLocalConnections()->then(function ($connections) {
foreach ($connections as $connection) {
$differenceInSeconds = $connection->lastPongedAt->diffInSeconds(Carbon::now());
if ($differenceInSeconds > 120) {
$this->unsubscribeFromAllChannels($connection);
}
}
});
return Helpers::createFulfilledPromise(
$this->lock()->forceRelease()
);
}
So that explains why I stop receiving messages, but there is no disconnect. It just unsubscribes the channels I'm listening to silently(can't see this on front-end) and keeps the connection alive.
I've also created an issue on github(laravel/echo) because I do think this is unwanted behaviour. I'm just not sure if the issue lies within echo, or within pusher js.
I have been through this. check your channel name and type, and make sure you have access. Also, check that there are no other js files interfere with your app.js file like what happened to me. check this laracasts question out

laravel "invalid host" on loadbalancer redirects

Background: I'm working on an api which I host on ec2 servers. I just finish the login and set up an nginx loadbalancer which redirect to the said server's internal ip's. The domain name points to the load balancer.
This used to work well with code igniter, but now I keep getting an "invalid host" problem.
I tried googling it and it found some things about trusted proxies so I installed what fideloper made and tried his post as well (I've followed a guide by fideloper on laravel-4-trusted-proxies and used and tried his trusted sample on github: fideloper/TrustedProxy) but I still get the same error:
UnexpectedValueException
Invalid Host "api.myserver.im, api.myserver.im"
// as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
// check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
if ($host && !preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host)) {
throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
}
Can someone help me?
I had the same issue as well. I had to resort to modifying the UrlGenerator.php file, which is part of the framework (bad I know...) just to get this to work.
So here's my "temporary" solution.
Create an array value to your app.php config file. e.g:
return array(
'rooturl' => 'https://www.youractualdomainname.com',
...
Next add the below modification in your UrlGenerator.php file <-- (trunk/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php)
<?php namespace Illuminate\Routing;
use Config;
...
protected function getRootUrl($scheme, $root = null)
{
$approoturl = Config::get('app.rooturl');
$root = isset($approoturl) ? $approoturl : $this->request->root();
return $root;
// if (is_null($root))
// {
// $root = $this->forcedRoot ?: $this->request->root();
// }
// $start = starts_with($root, 'http://') ? 'http://' : 'https://';
// return preg_replace('~'.$start.'~', $scheme, $root, 1);
}
Do note that composer update will revert your modification.

Swift Mailer : Address in mailbox given [] does not comply with RFC 2822, 3.6.2

I have a little problem here, when I try to send an email using swiftmailer, I got an error.
Here's my code:
<?php
session_start();
include("config.php");
$dir = dirname(__FILE__);
$session = $_SESSION[serialize];
// Load the SwiftMailer files
require_once($dir.'/swift/swift_required.php');
$hold = 'TIDAK';
// Kondisi - Kondisi yang ada
if($_GET[phase]=='confirm'){
$to = "test#127.0.0.1";
$kalimat = "Invoice Dengan nomor ".$_GET[nosc]." Telah di confirm, mohon di cek di sistem";
$kalimat2 = "Berikut terlampir data Invoice Customer , mohon di pastikan.";
$title = "CONFIRMATION NOTIFICATION";
}
// Convert string dlu
$mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer
$message = Swift_Message::newInstance()
->setSubject($title) // Message subject
->setTo(array($to)) // Array of people to send to
->setBcc(array($bcc)) // Bcc:
->setFrom(array($_SESSION[mailadmin] => $_SESSION[namauser].''.store('namasite'))) // From:
->setBody($kalimat, 'text/html'); // Attach that HTML message from earlier
// Send the email, and show user message
if($hold<>'YA'){
if ($mailer->send($message)){
echo json_encode(array('success'=>true));
} else {
echo json_encode(array('success'=>false));
}
}
?>
And then when I try to post the data to this file through jquery I got an error, this error I got from firebug.
<br />
<b>Fatal error</b>: Uncaught exception 'Swift_RfcComplianceException' with message 'Address in mailbox given [] does not comply with RFC 2822, 3.6.2.' in C:\xampp\htdocs\Colosus\core\swift\classes\Swift\Mime\Headers\MailboxHeader.php:319
Stack trace:
#0 C:\xampp\htdocs\Colosus\core\swift\classes\Swift\Mime\Headers\MailboxHeader.php(249): Swift_Mime_Headers_MailboxHeader->_assertValidAddress(NULL)
#1 C:\xampp\htdocs\Colosus\core\swift\classes\Swift\Mime\Headers\MailboxHeader.php(107): Swift_Mime_Headers_MailboxHeader->normalizeMailboxes(Array)
#2 C:\xampp\htdocs\Colosus\core\swift\classes\Swift\Mime\Headers\MailboxHeader.php(71): Swift_Mime_Headers_MailboxHeader->setNameAddresses(Array)
#3 C:\xampp\htdocs\Colosus\core\swift\classes\Swift\Mime\SimpleHeaderFactory.php(74): Swift_Mime_Headers_MailboxHeader->setFieldBodyModel(Array)
#4 C:\xampp\htdocs\Colosus\core\swift\classes\Swift\Mime\SimpleHeaderSet.php(87): Swift_Mime_SimpleHeaderFactory->createMailboxHeader('Bcc', Array)
#5 C:\xampp\htdocs\Colosus\core\swift\classes\Swift\Mime in <b>C:\xampp\htdocs\Colosus\core\swift\classes\Swift\Mime\Headers\MailboxHeader.php</b> on line <b>319</b><br />
So guys, anybody can help me here? I really doesn't know what happening here.
It's better if you use a try/catch around the send instruction:
try {
if ($mailer->send($message)){
...
}
} catch (Exception $e) {
$log_error->write_error($e->getMessage() . ';');
}
Or if you validate the email before sending it:
if(!Swift_Validate::email($email)){ //if email is not valid
//do something, skip them or log them
$log_error->log($email);
}
Please make sure there is no white space before or after the email address given.

Exporting exchange mails to Excel using lotusscript agent or Java agent or Javascript language

i want to export mails on exchnage server (subject line and body content) to Excel using lotusscript agent or Java agent or Javascript language. How can I acheive this? Any idea, suggestion or sample code is appreciable.
After doing reasearch found code to download mails from POP3 server. I used below code but got stuck at var oServer = new ActiveXObject("EAGetMailObj.MailServer"); with error - "Automation server can't create object". Then I put the host url in trusted sites and enabled active x control settings of IE, but then also getting the same error. Any idea, why?
The following code demonstrates how to receive email from a POP3 mail account. This sample downloads emails from POP3 server and deletes the email after the email is retrieved.
Code:
MailServerPop3 = 0;
MailServerImap4 = 1;
try
{
var oServer = new ActiveXObject("EAGetMailObj.MailServer");
// please change the server, user, password to yours
oServer.Server = "pop3.adminsystem.com"
oServer.Protocol = MailServerPop3;
oServer.User = "testx";
oServer.Password = "testpassword";
// If your server requires SSL connection,
// Please add the following codes.
oServer.SSLConnection = true;
oServer.Port = 995;
var oClient = new ActiveXObject("EAGetMailObj.MailClient");
oClient.LicenseCode = "TryIt";
// Connect POP3 server.
oClient.Connect(oServer);
var infos = new VBArray(oClient.GetMailInfos()).toArray();
for (var i = 0; i < infos.length; i++) {
var info = infos[i];
// Receive email from POP3 server
var oMail = oClient.GetMail(info);
// Save email to local disk
oMail.SaveAs("d:\\" + i + "_test.eml", true);
// Mark email as deleted on server.
oClient.Delete(info);
}
// Quit and pure emails marked as deleted from POP3 server.
oClient.Quit
}
catch( err )
{
WScript.Echo( err.description );
}
You can use Java and the Exchange Web Services API Java implementation at http://archive.msdn.microsoft.com/ewsjavaapi

Resources